Unset BRIDGEPEER when leaving a bridge
[asterisk/asterisk.git] / main / bridge_channel.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2007 - 2009, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Bridging Channel API
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  * \author Richard Mudgett <rmudgett@digium.com>
25  * \author Matt Jordan <mjordan@digium.com>
26  *
27  */
28
29 /*** MODULEINFO
30         <support_level>core</support_level>
31  ***/
32
33 #include "asterisk.h"
34
35 ASTERISK_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         ast_assert(frame->frametype != AST_FRAME_BRIDGE_ACTION_SYNC);
641
642         ast_bridge_channel_lock_bridge(bridge_channel);
643 /*
644  * XXX need to implement a deferred write queue for when there
645  * is no peer channel in the bridge (yet or it was kicked).
646  *
647  * The tech decides if a frame needs to be pushed back for deferral.
648  * simple_bridge/native_bridge are likely the only techs that will do this.
649  */
650         bridge_channel->bridge->technology->write(bridge_channel->bridge, bridge_channel, frame);
651
652         /* Remember any owed events to the bridge. */
653         switch (frame->frametype) {
654         case AST_FRAME_DTMF_BEGIN:
655                 bridge_channel->owed.dtmf_tv = ast_tvnow();
656                 bridge_channel->owed.dtmf_digit = frame->subclass.integer;
657                 break;
658         case AST_FRAME_DTMF_END:
659                 bridge_channel->owed.dtmf_digit = '\0';
660                 break;
661         case AST_FRAME_CONTROL:
662                 /*
663                  * We explicitly will not remember HOLD/UNHOLD frames because
664                  * things like attended transfers will handle them.
665                  */
666         default:
667                 break;
668         }
669         ast_bridge_unlock(bridge_channel->bridge);
670
671         /*
672          * Claim successful write to bridge.  If deferred frame
673          * support is added, claim successfully deferred.
674          */
675         return 0;
676 }
677
678 void bridge_channel_settle_owed_events(struct ast_bridge *orig_bridge, struct ast_bridge_channel *bridge_channel)
679 {
680         if (bridge_channel->owed.dtmf_digit) {
681                 struct ast_frame frame = {
682                         .frametype = AST_FRAME_DTMF_END,
683                         .subclass.integer = bridge_channel->owed.dtmf_digit,
684                         .src = "Bridge channel owed DTMF",
685                 };
686
687                 frame.len = ast_tvdiff_ms(ast_tvnow(), bridge_channel->owed.dtmf_tv);
688                 if (frame.len < option_dtmfminduration) {
689                         frame.len = option_dtmfminduration;
690                 }
691                 ast_log(LOG_DTMF, "DTMF end '%c' simulated to bridge %s because %s left.  Duration %ld ms.\n",
692                         bridge_channel->owed.dtmf_digit, orig_bridge->uniqueid,
693                         ast_channel_name(bridge_channel->chan), frame.len);
694                 bridge_channel->owed.dtmf_digit = '\0';
695                 orig_bridge->technology->write(orig_bridge, NULL, &frame);
696         }
697 }
698
699 /*!
700  * \internal
701  * \brief Suspend a channel from a bridge.
702  *
703  * \param bridge_channel Channel to suspend.
704  *
705  * \note This function assumes bridge_channel->bridge is locked.
706  *
707  * \return Nothing
708  */
709 void bridge_channel_internal_suspend_nolock(struct ast_bridge_channel *bridge_channel)
710 {
711         bridge_channel->suspended = 1;
712         if (bridge_channel->in_bridge) {
713                 --bridge_channel->bridge->num_active;
714         }
715
716         /* Get technology bridge threads off of the channel. */
717         if (bridge_channel->bridge->technology->suspend) {
718                 bridge_channel->bridge->technology->suspend(bridge_channel->bridge, bridge_channel);
719         }
720 }
721
722 /*!
723  * \internal
724  * \brief Suspend a channel from a bridge.
725  *
726  * \param bridge_channel Channel to suspend.
727  *
728  * \return Nothing
729  */
730 static void bridge_channel_suspend(struct ast_bridge_channel *bridge_channel)
731 {
732         ast_bridge_channel_lock_bridge(bridge_channel);
733         bridge_channel_internal_suspend_nolock(bridge_channel);
734         ast_bridge_unlock(bridge_channel->bridge);
735 }
736
737 /*!
738  * \internal
739  * \brief Unsuspend a channel from a bridge.
740  *
741  * \param bridge_channel Channel to unsuspend.
742  *
743  * \note This function assumes bridge_channel->bridge is locked.
744  *
745  * \return Nothing
746  */
747 void bridge_channel_internal_unsuspend_nolock(struct ast_bridge_channel *bridge_channel)
748 {
749         bridge_channel->suspended = 0;
750         if (bridge_channel->in_bridge) {
751                 ++bridge_channel->bridge->num_active;
752         }
753
754         /* Wake technology bridge threads to take care of channel again. */
755         if (bridge_channel->bridge->technology->unsuspend) {
756                 bridge_channel->bridge->technology->unsuspend(bridge_channel->bridge, bridge_channel);
757         }
758
759         /* Wake suspended channel. */
760         ast_bridge_channel_lock(bridge_channel);
761         ast_cond_signal(&bridge_channel->cond);
762         ast_bridge_channel_unlock(bridge_channel);
763 }
764
765 /*!
766  * \internal
767  * \brief Unsuspend a channel from a bridge.
768  *
769  * \param bridge_channel Channel to unsuspend.
770  *
771  * \return Nothing
772  */
773 static void bridge_channel_unsuspend(struct ast_bridge_channel *bridge_channel)
774 {
775         ast_bridge_channel_lock_bridge(bridge_channel);
776         bridge_channel_internal_unsuspend_nolock(bridge_channel);
777         ast_bridge_unlock(bridge_channel->bridge);
778 }
779
780 /*!
781  * \internal
782  * \brief Queue an action frame onto the bridge channel with data.
783  * \since 12.0.0
784  *
785  * \param bridge_channel Which channel to queue the frame onto.
786  * \param action Type of bridge action frame.
787  * \param data Frame payload data to pass.
788  * \param datalen Frame payload data length to pass.
789  *
790  * \retval 0 on success.
791  * \retval -1 on error.
792  */
793 static int bridge_channel_queue_action_data(struct ast_bridge_channel *bridge_channel,
794         enum bridge_channel_action_type action, const void *data, size_t datalen)
795 {
796         struct ast_frame frame = {
797                 .frametype = AST_FRAME_BRIDGE_ACTION,
798                 .subclass.integer = action,
799                 .datalen = datalen,
800                 .data.ptr = (void *) data,
801         };
802
803         return ast_bridge_channel_queue_frame(bridge_channel, &frame);
804 }
805
806 /*!
807  * \internal
808  * \brief Queue an action frame onto the bridge channel with data synchronously.
809  * \since 12.2.0
810  *
811  * The function will not return until the queued frame is freed.
812  *
813  * \param bridge_channel Which channel to queue the frame onto.
814  * \param action Type of bridge action frame.
815  * \param data Frame payload data to pass.
816  * \param datalen Frame payload data length to pass.
817  *
818  * \retval 0 on success.
819  * \retval -1 on error.
820  */
821 static int bridge_channel_queue_action_data_sync(struct ast_bridge_channel *bridge_channel,
822         enum bridge_channel_action_type action, const void *data, size_t datalen)
823 {
824         struct sync_payload *sync_payload;
825         int sync_payload_len = sizeof(*sync_payload) + datalen;
826         struct bridge_sync sync_struct;
827         struct ast_frame frame = {
828                 .frametype = AST_FRAME_BRIDGE_ACTION_SYNC,
829                 .subclass.integer = action,
830         };
831
832         /* Make sure we don't end up trying to wait on ourself to deliver the frame */
833         ast_assert(!pthread_equal(pthread_self(), bridge_channel->thread));
834
835         sync_payload = ast_alloca(sync_payload_len);
836         sync_payload->id = ast_atomic_fetchadd_int(&sync_ids, +1);
837         memcpy(sync_payload->data, data, datalen);
838
839         frame.datalen = sync_payload_len;
840         frame.data.ptr = sync_payload;
841
842         bridge_sync_init(&sync_struct, sync_payload->id);
843         if (ast_bridge_channel_queue_frame(bridge_channel, &frame)) {
844                 bridge_sync_cleanup(&sync_struct);
845                 return -1;
846         }
847
848         bridge_sync_wait(&sync_struct);
849         bridge_sync_cleanup(&sync_struct);
850         return 0;
851 }
852 /*!
853  * \internal
854  * \brief Write an action frame onto the bridge channel with data.
855  * \since 12.0.0
856  *
857  * \param bridge_channel Which channel to queue the frame onto.
858  * \param action Type of bridge action frame.
859  * \param data Frame payload data to pass.
860  * \param datalen Frame payload data length to pass.
861  *
862  * \retval 0 on success.
863  * \retval -1 on error.
864  */
865 static int bridge_channel_write_action_data(struct ast_bridge_channel *bridge_channel,
866         enum bridge_channel_action_type action, const void *data, size_t datalen)
867 {
868         struct ast_frame frame = {
869                 .frametype = AST_FRAME_BRIDGE_ACTION,
870                 .subclass.integer = action,
871                 .datalen = datalen,
872                 .data.ptr = (void *) data,
873         };
874
875         return bridge_channel_write_frame(bridge_channel, &frame);
876 }
877
878 static void bridge_frame_free(struct ast_frame *frame)
879 {
880         if (frame->frametype == AST_FRAME_BRIDGE_ACTION_SYNC) {
881                 struct sync_payload *sync_payload = frame->data.ptr;
882                 struct bridge_sync *sync;
883
884                 AST_RWLIST_RDLOCK(&sync_structs);
885                 AST_RWLIST_TRAVERSE(&sync_structs, sync, list) {
886                         if (sync->id == sync_payload->id) {
887                                 break;
888                         }
889                 }
890                 if (sync) {
891                         bridge_sync_signal(sync);
892                 }
893                 AST_RWLIST_UNLOCK(&sync_structs);
894         }
895
896         ast_frfree(frame);
897 }
898
899 int ast_bridge_channel_queue_frame(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
900 {
901         struct ast_frame *dup;
902         char nudge = 0;
903
904         if (bridge_channel->suspended
905                 /* Also defer DTMF frames. */
906                 && fr->frametype != AST_FRAME_DTMF_BEGIN
907                 && fr->frametype != AST_FRAME_DTMF_END
908                 && !ast_is_deferrable_frame(fr)) {
909                 /* Drop non-deferable frames when suspended. */
910                 return 0;
911         }
912         if (fr->frametype == AST_FRAME_NULL) {
913                 /* "Accept" the frame and discard it. */
914                 return 0;
915         }
916
917         dup = ast_frdup(fr);
918         if (!dup) {
919                 return -1;
920         }
921
922         ast_bridge_channel_lock(bridge_channel);
923         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
924                 /* Drop frames on channels leaving the bridge. */
925                 ast_bridge_channel_unlock(bridge_channel);
926                 bridge_frame_free(dup);
927                 return 0;
928         }
929
930         AST_LIST_INSERT_TAIL(&bridge_channel->wr_queue, dup, frame_list);
931         if (write(bridge_channel->alert_pipe[1], &nudge, sizeof(nudge)) != sizeof(nudge)) {
932                 ast_log(LOG_ERROR, "We couldn't write alert pipe for %p(%s)... something is VERY wrong\n",
933                         bridge_channel, ast_channel_name(bridge_channel->chan));
934         }
935         ast_bridge_channel_unlock(bridge_channel);
936         return 0;
937 }
938
939 int ast_bridge_queue_everyone_else(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
940 {
941         struct ast_bridge_channel *cur;
942         int not_written = -1;
943
944         if (frame->frametype == AST_FRAME_NULL) {
945                 /* "Accept" the frame and discard it. */
946                 return 0;
947         }
948
949         AST_LIST_TRAVERSE(&bridge->channels, cur, entry) {
950                 if (cur == bridge_channel) {
951                         continue;
952                 }
953                 if (!ast_bridge_channel_queue_frame(cur, frame)) {
954                         not_written = 0;
955                 }
956         }
957         return not_written;
958 }
959
960 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)
961 {
962         struct ast_frame frame = {
963                 .frametype = AST_FRAME_CONTROL,
964                 .subclass.integer = control,
965                 .datalen = datalen,
966                 .data.ptr = (void *) data,
967         };
968
969         return ast_bridge_channel_queue_frame(bridge_channel, &frame);
970 }
971
972 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)
973 {
974         struct ast_frame frame = {
975                 .frametype = AST_FRAME_CONTROL,
976                 .subclass.integer = control,
977                 .datalen = datalen,
978                 .data.ptr = (void *) data,
979         };
980
981         return bridge_channel_write_frame(bridge_channel, &frame);
982 }
983
984 int ast_bridge_channel_write_hold(struct ast_bridge_channel *bridge_channel, const char *moh_class)
985 {
986         struct ast_json *blob;
987         int res;
988         size_t datalen;
989
990         if (!ast_strlen_zero(moh_class)) {
991                 datalen = strlen(moh_class) + 1;
992
993                 blob = ast_json_pack("{s: s}",
994                         "musicclass", moh_class);
995         } else {
996                 moh_class = NULL;
997                 datalen = 0;
998                 blob = NULL;
999         }
1000
1001         ast_channel_publish_cached_blob(bridge_channel->chan, ast_channel_hold_type(), blob);
1002
1003         res = ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_HOLD,
1004                 moh_class, datalen);
1005
1006         ast_json_unref(blob);
1007         return res;
1008 }
1009
1010 int ast_bridge_channel_write_unhold(struct ast_bridge_channel *bridge_channel)
1011 {
1012         ast_channel_publish_cached_blob(bridge_channel->chan, ast_channel_unhold_type(), NULL);
1013
1014         return ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_UNHOLD, NULL, 0);
1015 }
1016
1017 /*!
1018  * \internal
1019  * \brief Helper function to kick off a PBX app on a bridge_channel
1020  */
1021 static int run_app_helper(struct ast_channel *chan, const char *app_name, const char *app_args)
1022 {
1023         int res = 0;
1024
1025         if (!strcasecmp("Gosub", app_name)) {
1026                 ast_app_exec_sub(NULL, chan, app_args, 0);
1027         } else if (!strcasecmp("Macro", app_name)) {
1028                 ast_app_exec_macro(NULL, chan, app_args);
1029         } else {
1030                 struct ast_app *app;
1031
1032                 app = pbx_findapp(app_name);
1033                 if (!app) {
1034                         ast_log(LOG_WARNING, "Could not find application (%s)\n", app_name);
1035                 } else {
1036                         struct ast_str *substituted_args = ast_str_create(16);
1037
1038                         if (substituted_args) {
1039                                 ast_str_substitute_variables(&substituted_args, 0, chan, app_args);
1040                                 res = pbx_exec(chan, app, ast_str_buffer(substituted_args));
1041                                 ast_free(substituted_args);
1042                         } else {
1043                                 ast_log(LOG_WARNING, "Could not substitute application argument variables for %s\n", app_name);
1044                                 res = pbx_exec(chan, app, app_args);
1045                         }
1046                 }
1047         }
1048         return res;
1049 }
1050
1051 void ast_bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1052 {
1053         if (moh_class) {
1054                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
1055         }
1056         if (run_app_helper(bridge_channel->chan, app_name, S_OR(app_args, ""))) {
1057                 /* Break the bridge if the app returns non-zero. */
1058                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1059         }
1060         if (moh_class) {
1061                 ast_bridge_channel_write_unhold(bridge_channel);
1062         }
1063 }
1064
1065 struct bridge_run_app {
1066         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
1067         int moh_offset;
1068         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
1069         int app_args_offset;
1070         /*! Application name to run. */
1071         char app_name[0];
1072 };
1073
1074 /*!
1075  * \internal
1076  * \brief Handle the run application bridge action.
1077  * \since 12.0.0
1078  *
1079  * \param bridge_channel Which channel to run the application on.
1080  * \param data Action frame data to run the application.
1081  *
1082  * \return Nothing
1083  */
1084 static void bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, struct bridge_run_app *data)
1085 {
1086         ast_bridge_channel_run_app(bridge_channel, data->app_name,
1087                 data->app_args_offset ? &data->app_name[data->app_args_offset] : NULL,
1088                 data->moh_offset ? &data->app_name[data->moh_offset] : NULL);
1089 }
1090
1091 /*!
1092  * \internal
1093  * \brief Marshal an application to be executed on a bridge_channel
1094  */
1095 static int payload_helper_app(ast_bridge_channel_post_action_data post_it,
1096         struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1097 {
1098         struct bridge_run_app *app_data;
1099         size_t len_name = strlen(app_name) + 1;
1100         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
1101         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
1102         size_t len_data = sizeof(*app_data) + len_name + len_args + len_moh;
1103
1104         /* Fill in application run frame data. */
1105         app_data = alloca(len_data);
1106         app_data->app_args_offset = len_args ? len_name : 0;
1107         app_data->moh_offset = len_moh ? len_name + len_args : 0;
1108         strcpy(app_data->app_name, app_name);/* Safe */
1109         if (len_args) {
1110                 strcpy(&app_data->app_name[app_data->app_args_offset], app_args);/* Safe */
1111         }
1112         if (moh_class) {
1113                 strcpy(&app_data->app_name[app_data->moh_offset], moh_class);/* Safe */
1114         }
1115
1116         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_RUN_APP, app_data, len_data);
1117 }
1118
1119 int ast_bridge_channel_write_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1120 {
1121         return payload_helper_app(bridge_channel_write_action_data,
1122                 bridge_channel, app_name, app_args, moh_class);
1123 }
1124
1125 int ast_bridge_channel_queue_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
1126 {
1127         return payload_helper_app(bridge_channel_queue_action_data,
1128                 bridge_channel, app_name, app_args, moh_class);
1129 }
1130
1131 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)
1132 {
1133         if (moh_class) {
1134                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
1135         }
1136         if (custom_play) {
1137                 custom_play(bridge_channel, playfile);
1138         } else {
1139                 ast_stream_and_wait(bridge_channel->chan, playfile, AST_DIGIT_NONE);
1140         }
1141         if (moh_class) {
1142                 ast_bridge_channel_write_unhold(bridge_channel);
1143         }
1144
1145         /*
1146          * It may be necessary to resume music on hold after we finish
1147          * playing the announcment.
1148          */
1149         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_MOH)) {
1150                 const char *latest_musicclass;
1151
1152                 ast_channel_lock(bridge_channel->chan);
1153                 latest_musicclass = ast_strdupa(ast_channel_latest_musicclass(bridge_channel->chan));
1154                 ast_channel_unlock(bridge_channel->chan);
1155                 ast_moh_start(bridge_channel->chan, latest_musicclass, NULL);
1156         }
1157 }
1158
1159 struct bridge_playfile {
1160         /*! Call this function to play the playfile. (NULL if normal sound file to play) */
1161         ast_bridge_custom_play_fn custom_play;
1162         /*! Offset into playfile[] where the MOH class name starts.  (zero if no MOH)*/
1163         int moh_offset;
1164         /*! Filename to play. */
1165         char playfile[0];
1166 };
1167
1168 /*!
1169  * \internal
1170  * \brief Handle the playfile bridge action.
1171  * \since 12.0.0
1172  *
1173  * \param bridge_channel Which channel to play a file on.
1174  * \param payload Action frame payload to play a file.
1175  *
1176  * \return Nothing
1177  */
1178 static void bridge_channel_playfile(struct ast_bridge_channel *bridge_channel, struct bridge_playfile *payload)
1179 {
1180         ast_bridge_channel_playfile(bridge_channel, payload->custom_play, payload->playfile,
1181                 payload->moh_offset ? &payload->playfile[payload->moh_offset] : NULL);
1182 }
1183
1184 /*!
1185  * \internal
1186  * \brief Marshal a file to be played on a bridge_channel
1187  */
1188 static int payload_helper_playfile(ast_bridge_channel_post_action_data post_it,
1189         struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
1190 {
1191         struct bridge_playfile *payload;
1192         size_t len_name = strlen(playfile) + 1;
1193         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
1194         size_t len_payload = sizeof(*payload) + len_name + len_moh;
1195
1196         /* Fill in play file frame data. */
1197         payload = ast_alloca(len_payload);
1198         payload->custom_play = custom_play;
1199         payload->moh_offset = len_moh ? len_name : 0;
1200         strcpy(payload->playfile, playfile);/* Safe */
1201         if (moh_class) {
1202                 strcpy(&payload->playfile[payload->moh_offset], moh_class);/* Safe */
1203         }
1204
1205         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PLAY_FILE, payload, len_payload);
1206 }
1207
1208 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)
1209 {
1210         return payload_helper_playfile(bridge_channel_write_action_data,
1211                 bridge_channel, custom_play, playfile, moh_class);
1212 }
1213
1214 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)
1215 {
1216         return payload_helper_playfile(bridge_channel_queue_action_data,
1217                 bridge_channel, custom_play, playfile, moh_class);
1218 }
1219
1220 int ast_bridge_channel_queue_playfile_sync(struct ast_bridge_channel *bridge_channel,
1221                 ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
1222 {
1223         return payload_helper_playfile(bridge_channel_queue_action_data_sync,
1224                 bridge_channel, custom_play, playfile, moh_class);
1225 }
1226
1227 struct bridge_custom_callback {
1228         /*! Call this function on the bridge channel thread. */
1229         ast_bridge_custom_callback_fn callback;
1230         /*! Size of the payload if it exists.  A number otherwise. */
1231         size_t payload_size;
1232         /*! Option flags determining how callback is called. */
1233         unsigned int flags;
1234         /*! Nonzero if the payload exists. */
1235         char payload_exists;
1236         /*! Payload to give to callback. */
1237         char payload[0];
1238 };
1239
1240 /*!
1241  * \internal
1242  * \brief Handle the do custom callback bridge action.
1243  * \since 12.0.0
1244  *
1245  * \param bridge_channel Which channel to call the callback on.
1246  * \param data Action frame data to call the callback.
1247  *
1248  * \return Nothing
1249  */
1250 static void bridge_channel_do_callback(struct ast_bridge_channel *bridge_channel, struct bridge_custom_callback *data)
1251 {
1252         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
1253                 bridge_channel_suspend(bridge_channel);
1254                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1255         }
1256         data->callback(bridge_channel, data->payload_exists ? data->payload : NULL, data->payload_size);
1257         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
1258                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1259                 bridge_channel_unsuspend(bridge_channel);
1260         }
1261 }
1262
1263 /*!
1264  * \internal
1265  * \brief Marshal a custom callback function to be called on a bridge_channel
1266  */
1267 static int payload_helper_cb(ast_bridge_channel_post_action_data post_it,
1268         struct ast_bridge_channel *bridge_channel,
1269         enum ast_bridge_channel_custom_callback_option flags,
1270         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1271 {
1272         struct bridge_custom_callback *cb_data;
1273         size_t len_data = sizeof(*cb_data) + (payload ? payload_size : 0);
1274
1275         /* Sanity check. */
1276         if (!callback) {
1277                 ast_assert(0);
1278                 return -1;
1279         }
1280
1281         /* Fill in custom callback frame data. */
1282         cb_data = alloca(len_data);
1283         cb_data->callback = callback;
1284         cb_data->payload_size = payload_size;
1285         cb_data->flags = flags;
1286         cb_data->payload_exists = payload && payload_size;
1287         if (cb_data->payload_exists) {
1288                 memcpy(cb_data->payload, payload, payload_size);/* Safe */
1289         }
1290
1291         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_CALLBACK, cb_data, len_data);
1292 }
1293
1294 int ast_bridge_channel_write_callback(struct ast_bridge_channel *bridge_channel,
1295         enum ast_bridge_channel_custom_callback_option flags,
1296         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1297 {
1298         return payload_helper_cb(bridge_channel_write_action_data,
1299                 bridge_channel, flags, callback, payload, payload_size);
1300 }
1301
1302 int ast_bridge_channel_queue_callback(struct ast_bridge_channel *bridge_channel,
1303         enum ast_bridge_channel_custom_callback_option flags,
1304         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1305 {
1306         return payload_helper_cb(bridge_channel_queue_action_data,
1307                 bridge_channel, flags, callback, payload, payload_size);
1308 }
1309
1310 struct bridge_park {
1311         int parker_uuid_offset;
1312         int app_data_offset;
1313         /* buffer used for holding those strings */
1314         char parkee_uuid[0];
1315 };
1316
1317 /*!
1318  * \internal
1319  * \brief Park a bridge_cahnnel
1320  */
1321 static void bridge_channel_park(struct ast_bridge_channel *bridge_channel, struct bridge_park *payload)
1322 {
1323         if (!ast_parking_provider_registered()) {
1324                 ast_log(AST_LOG_WARNING, "Unable to park %s: No parking provider loaded!\n",
1325                         ast_channel_name(bridge_channel->chan));
1326                 return;
1327         }
1328
1329         if (ast_parking_park_bridge_channel(bridge_channel, payload->parkee_uuid,
1330                 &payload->parkee_uuid[payload->parker_uuid_offset],
1331                 payload->app_data_offset ? &payload->parkee_uuid[payload->app_data_offset] : NULL)) {
1332                 ast_log(AST_LOG_WARNING, "Error occurred while parking %s\n",
1333                         ast_channel_name(bridge_channel->chan));
1334         }
1335 }
1336
1337 /*!
1338  * \internal
1339  * \brief Marshal a park action onto a bridge_channel
1340  */
1341 static int payload_helper_park(ast_bridge_channel_post_action_data post_it,
1342         struct ast_bridge_channel *bridge_channel,
1343         const char *parkee_uuid,
1344         const char *parker_uuid,
1345         const char *app_data)
1346 {
1347         struct bridge_park *payload;
1348         size_t len_parkee_uuid = strlen(parkee_uuid) + 1;
1349         size_t len_parker_uuid = strlen(parker_uuid) + 1;
1350         size_t len_app_data = !app_data ? 0 : strlen(app_data) + 1;
1351         size_t len_payload = sizeof(*payload) + len_parker_uuid + len_parkee_uuid + len_app_data;
1352
1353         payload = alloca(len_payload);
1354         payload->app_data_offset = len_app_data ? len_parkee_uuid + len_parker_uuid : 0;
1355         payload->parker_uuid_offset = len_parkee_uuid;
1356         strcpy(payload->parkee_uuid, parkee_uuid);
1357         strcpy(&payload->parkee_uuid[payload->parker_uuid_offset], parker_uuid);
1358         if (app_data) {
1359                 strcpy(&payload->parkee_uuid[payload->app_data_offset], app_data);
1360         }
1361
1362         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PARK, payload, len_payload);
1363 }
1364
1365 int ast_bridge_channel_write_park(struct ast_bridge_channel *bridge_channel, const char *parkee_uuid, const char *parker_uuid, const char *app_data)
1366 {
1367         return payload_helper_park(bridge_channel_write_action_data,
1368                 bridge_channel, parkee_uuid, parker_uuid, app_data);
1369 }
1370
1371 /*!
1372  * \internal
1373  * \brief Handle bridge channel interval expiration.
1374  * \since 12.0.0
1375  *
1376  * \param bridge_channel Channel to run expired intervals on.
1377  *
1378  * \return Nothing
1379  */
1380 static void bridge_channel_handle_interval(struct ast_bridge_channel *bridge_channel)
1381 {
1382         struct ast_heap *interval_hooks;
1383         struct ast_bridge_hook_timer *hook;
1384         struct timeval start;
1385         int chan_suspended = 0;
1386
1387         interval_hooks = bridge_channel->features->interval_hooks;
1388         ast_heap_wrlock(interval_hooks);
1389         start = ast_tvnow();
1390         while ((hook = ast_heap_peek(interval_hooks, 1))) {
1391                 int interval;
1392                 unsigned int execution_time;
1393
1394                 if (ast_tvdiff_ms(hook->timer.trip_time, start) > 0) {
1395                         ast_debug(1, "Hook %p on %p(%s) wants to happen in the future, stopping our traversal\n",
1396                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1397                         break;
1398                 }
1399                 ao2_ref(hook, +1);
1400                 ast_heap_unlock(interval_hooks);
1401
1402                 if (!chan_suspended
1403                         && ast_test_flag(&hook->timer, AST_BRIDGE_HOOK_TIMER_OPTION_MEDIA)) {
1404                         chan_suspended = 1;
1405                         bridge_channel_suspend(bridge_channel);
1406                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1407                 }
1408
1409                 ast_debug(1, "Executing hook %p on %p(%s)\n",
1410                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1411                 interval = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1412
1413                 ast_heap_wrlock(interval_hooks);
1414                 if (ast_heap_peek(interval_hooks, hook->timer.heap_index) != hook
1415                         || !ast_heap_remove(interval_hooks, hook)) {
1416                         /* Interval hook is already removed from the bridge_channel. */
1417                         ao2_ref(hook, -1);
1418                         continue;
1419                 }
1420                 ao2_ref(hook, -1);
1421
1422                 if (interval < 0) {
1423                         ast_debug(1, "Removed interval hook %p from %p(%s)\n",
1424                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1425                         ao2_ref(hook, -1);
1426                         continue;
1427                 }
1428                 if (interval) {
1429                         /* Set new interval for the hook. */
1430                         hook->timer.interval = interval;
1431                 }
1432
1433                 ast_debug(1, "Updating interval hook %p with interval %u on %p(%s)\n",
1434                         hook, hook->timer.interval, bridge_channel,
1435                         ast_channel_name(bridge_channel->chan));
1436
1437                 /* resetting start */
1438                 start = ast_tvnow();
1439
1440                 /*
1441                  * Resetup the interval hook for the next interval.  We may need
1442                  * to skip over any missed intervals because the hook was
1443                  * delayed or took too long.
1444                  */
1445                 execution_time = ast_tvdiff_ms(start, hook->timer.trip_time);
1446                 while (hook->timer.interval < execution_time) {
1447                         execution_time -= hook->timer.interval;
1448                 }
1449                 hook->timer.trip_time = ast_tvadd(start, ast_samp2tv(hook->timer.interval - execution_time, 1000));
1450                 hook->timer.seqno = ast_atomic_fetchadd_int((int *) &bridge_channel->features->interval_sequence, +1);
1451
1452                 if (ast_heap_push(interval_hooks, hook)) {
1453                         /* Could not push the hook back onto the heap. */
1454                         ao2_ref(hook, -1);
1455                 }
1456         }
1457         ast_heap_unlock(interval_hooks);
1458
1459         if (chan_suspended) {
1460                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1461                 bridge_channel_unsuspend(bridge_channel);
1462         }
1463 }
1464
1465 /*!
1466  * \internal
1467  * \brief Write a DTMF stream out to a channel
1468  */
1469 static int bridge_channel_write_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1470 {
1471         return bridge_channel_write_action_data(bridge_channel,
1472                 BRIDGE_CHANNEL_ACTION_DTMF_STREAM, dtmf, strlen(dtmf) + 1);
1473 }
1474
1475 /*!
1476  * \internal
1477  * \brief Indicate to the testsuite a feature was successfully detected.
1478  *
1479  * Currently, this function only will relay built-in features to the testsuite,
1480  * but it could be modified to detect applicationmap items should the need arise.
1481  *
1482  * \param chan The channel that activated the feature
1483  * \param dtmf The DTMF sequence entered to activate the feature
1484  */
1485 static void testsuite_notify_feature_success(struct ast_channel *chan, const char *dtmf)
1486 {
1487 #ifdef TEST_FRAMEWORK
1488         char *feature = "unknown";
1489         struct ast_featuremap_config *featuremap = ast_get_chan_featuremap_config(chan);
1490         struct ast_features_xfer_config *xfer = ast_get_chan_features_xfer_config(chan);
1491
1492         if (featuremap) {
1493                 if (!strcmp(dtmf, featuremap->blindxfer)) {
1494                         feature = "blindxfer";
1495                 } else if (!strcmp(dtmf, featuremap->atxfer)) {
1496                         feature = "atxfer";
1497                 } else if (!strcmp(dtmf, featuremap->disconnect)) {
1498                         feature = "disconnect";
1499                 } else if (!strcmp(dtmf, featuremap->automon)) {
1500                         feature = "automon";
1501                 } else if (!strcmp(dtmf, featuremap->automixmon)) {
1502                         feature = "automixmon";
1503                 } else if (!strcmp(dtmf, featuremap->parkcall)) {
1504                         feature = "parkcall";
1505                 }
1506         }
1507         if (xfer) {
1508                 if (!strcmp(dtmf, xfer->atxferthreeway)) {
1509                         feature = "atxferthreeway";
1510                 }
1511         }
1512
1513         ao2_cleanup(featuremap);
1514         ao2_cleanup(xfer);
1515
1516         ast_test_suite_event_notify("FEATURE_DETECTION",
1517                         "Result: success\r\n"
1518                         "Feature: %s", feature);
1519 #endif /* TEST_FRAMEWORK */
1520 }
1521
1522 static int bridge_channel_feature_digit_add(
1523         struct ast_bridge_channel *bridge_channel, int digit, size_t dtmf_len)
1524 {
1525         if (dtmf_len < ARRAY_LEN(bridge_channel->dtmf_hook_state.collected) - 1) {
1526                 /* Add the new digit to the DTMF string so we can do our matching */
1527                 bridge_channel->dtmf_hook_state.collected[dtmf_len++] = digit;
1528                 bridge_channel->dtmf_hook_state.collected[dtmf_len] = '\0';
1529
1530                 ast_debug(1, "DTMF feature string on %p(%s) is now '%s'\n",
1531                           bridge_channel, ast_channel_name(bridge_channel->chan),
1532                           bridge_channel->dtmf_hook_state.collected);
1533         }
1534
1535         return dtmf_len;
1536 }
1537
1538 static unsigned int bridge_channel_feature_digit_timeout(struct ast_bridge_channel *bridge_channel)
1539 {
1540         unsigned int digit_timeout;
1541         struct ast_features_general_config *gen_cfg;
1542
1543         /* Determine interdigit timeout */
1544         ast_channel_lock(bridge_channel->chan);
1545         gen_cfg = ast_get_chan_features_general_config(bridge_channel->chan);
1546         ast_channel_unlock(bridge_channel->chan);
1547
1548         if (!gen_cfg) {
1549                 ast_log(LOG_ERROR, "Unable to retrieve features configuration.\n");
1550                 return 3000; /* Pick a reasonable failsafe timeout in ms */
1551         }
1552
1553         digit_timeout = gen_cfg->featuredigittimeout;
1554         ao2_ref(gen_cfg, -1);
1555
1556         return digit_timeout;
1557 }
1558
1559 void ast_bridge_channel_feature_digit_add(struct ast_bridge_channel *bridge_channel, int digit)
1560 {
1561         if (digit) {
1562                 bridge_channel_feature_digit_add(
1563                         bridge_channel, digit, strlen(bridge_channel->dtmf_hook_state.collected));
1564         }
1565 }
1566
1567 void ast_bridge_channel_feature_digit(struct ast_bridge_channel *bridge_channel, int digit)
1568 {
1569         struct ast_bridge_features *features = bridge_channel->features;
1570         struct ast_bridge_hook_dtmf *hook = NULL;
1571         size_t dtmf_len;
1572
1573         struct sanity_check_of_dtmf_size {
1574                 char check[1 / (ARRAY_LEN(bridge_channel->dtmf_hook_state.collected) == ARRAY_LEN(hook->dtmf.code))];
1575         };
1576
1577         dtmf_len = strlen(bridge_channel->dtmf_hook_state.collected);
1578         if (!dtmf_len && !digit) {
1579                 /* Nothing to do */
1580                 return;
1581         }
1582
1583         if (digit) {
1584                 dtmf_len = bridge_channel_feature_digit_add(bridge_channel, digit, dtmf_len);
1585         }
1586
1587         while (digit) {
1588                 /* See if a DTMF feature hook matches or can match */
1589                 hook = ao2_find(features->dtmf_hooks, bridge_channel->dtmf_hook_state.collected,
1590                         OBJ_SEARCH_PARTIAL_KEY);
1591                 if (!hook) {
1592                         ast_debug(1, "No DTMF feature hooks on %p(%s) match '%s'\n",
1593                                 bridge_channel, ast_channel_name(bridge_channel->chan),
1594                                 bridge_channel->dtmf_hook_state.collected);
1595                         break;
1596                 } else if (dtmf_len != strlen(hook->dtmf.code)) {
1597                         unsigned int digit_timeout;
1598                         /* Need more digits to match */
1599                         ao2_ref(hook, -1);
1600                         digit_timeout = bridge_channel_feature_digit_timeout(bridge_channel);
1601                         bridge_channel->dtmf_hook_state.interdigit_timeout =
1602                                 ast_tvadd(ast_tvnow(), ast_samp2tv(digit_timeout, 1000));
1603                         return;
1604                 } else {
1605                         int remove_me;
1606                         int already_suspended;
1607
1608                         ast_debug(1, "DTMF feature hook %p matched DTMF string '%s' on %p(%s)\n",
1609                                 hook, bridge_channel->dtmf_hook_state.collected, bridge_channel,
1610                                 ast_channel_name(bridge_channel->chan));
1611
1612                         /*
1613                          * Clear the collected digits before executing the hook
1614                          * in case the hook starts another sequence.
1615                          */
1616                         bridge_channel->dtmf_hook_state.collected[0] = '\0';
1617
1618                         ast_bridge_channel_lock_bridge(bridge_channel);
1619                         already_suspended = bridge_channel->suspended;
1620                         if (!already_suspended) {
1621                                 bridge_channel_internal_suspend_nolock(bridge_channel);
1622                         }
1623                         ast_bridge_unlock(bridge_channel->bridge);
1624                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1625
1626                         /* Execute the matched hook on this channel. */
1627                         remove_me = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1628                         if (remove_me) {
1629                                 ast_debug(1, "DTMF hook %p is being removed from %p(%s)\n",
1630                                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1631                                 ao2_unlink(features->dtmf_hooks, hook);
1632                         }
1633                         testsuite_notify_feature_success(bridge_channel->chan, hook->dtmf.code);
1634                         ao2_ref(hook, -1);
1635
1636                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1637                         if (!already_suspended) {
1638                                 bridge_channel_unsuspend(bridge_channel);
1639                         }
1640
1641                         /*
1642                          * If we are handing the channel off to an external hook for
1643                          * ownership, we are not guaranteed what kind of state it will
1644                          * come back in.  If the channel hungup, we need to detect that
1645                          * here if the hook did not already change the state.
1646                          */
1647                         if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
1648                                 ast_bridge_channel_kick(bridge_channel, 0);
1649                                 bridge_channel->dtmf_hook_state.collected[0] = '\0';
1650                                 return;
1651                         }
1652
1653                         /* if there is dtmf that has been collected then loop back through,
1654                            but set digit to -1 so it doesn't try to do an add since the dtmf
1655                            is already in the buffer */
1656                         dtmf_len = strlen(bridge_channel->dtmf_hook_state.collected);
1657                         if (!dtmf_len) {
1658                                 return;
1659                         }
1660                 }
1661         }
1662
1663         if (!digit) {
1664                 ast_debug(1, "DTMF feature string collection on %p(%s) timed out\n",
1665                         bridge_channel, ast_channel_name(bridge_channel->chan));
1666         }
1667
1668         /* Timeout or DTMF digit didn't allow a match with any hooks. */
1669         if (features->dtmf_passthrough) {
1670                 /* Stream the collected DTMF to the other channels. */
1671                 bridge_channel_write_dtmf_stream(bridge_channel,
1672                         bridge_channel->dtmf_hook_state.collected);
1673         }
1674         bridge_channel->dtmf_hook_state.collected[0] = '\0';
1675
1676         ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
1677 }
1678
1679 /*!
1680  * \internal
1681  * \brief Handle bridge channel DTMF feature timeout expiration.
1682  * \since 12.8.0
1683  *
1684  * \param bridge_channel Channel to check expired interdigit timer on.
1685  *
1686  * \return Nothing
1687  */
1688 static void bridge_channel_handle_feature_timeout(struct ast_bridge_channel *bridge_channel)
1689 {
1690         if (!bridge_channel->dtmf_hook_state.collected[0]
1691                 || 0 < ast_tvdiff_ms(bridge_channel->dtmf_hook_state.interdigit_timeout,
1692                         ast_tvnow())) {
1693                 /* Not within a sequence or not timed out. */
1694                 return;
1695         }
1696
1697         ast_bridge_channel_feature_digit(bridge_channel, 0);
1698 }
1699
1700 /*!
1701  * \internal
1702  * \brief Indicate that a bridge_channel is talking
1703  */
1704 static void bridge_channel_talking(struct ast_bridge_channel *bridge_channel, int talking)
1705 {
1706         struct ast_bridge_features *features = bridge_channel->features;
1707         struct ast_bridge_hook *hook;
1708         struct ao2_iterator iter;
1709
1710         /* Run any talk detection hooks. */
1711         iter = ao2_iterator_init(features->other_hooks, 0);
1712         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1713                 int remove_me;
1714                 ast_bridge_talking_indicate_callback talk_cb;
1715
1716                 if (hook->type != AST_BRIDGE_HOOK_TYPE_TALK) {
1717                         continue;
1718                 }
1719                 talk_cb = (ast_bridge_talking_indicate_callback) hook->callback;
1720                 remove_me = talk_cb(bridge_channel, hook->hook_pvt, talking);
1721                 if (remove_me) {
1722                         ast_debug(1, "Talk detection hook %p is being removed from %p(%s)\n",
1723                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1724                         ao2_unlink(features->other_hooks, hook);
1725                 }
1726         }
1727         ao2_iterator_destroy(&iter);
1728 }
1729
1730 /*! \brief Internal function that plays back DTMF on a bridge channel */
1731 static void bridge_channel_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1732 {
1733         ast_debug(1, "Playing DTMF stream '%s' out to %p(%s)\n",
1734                 dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1735         ast_dtmf_stream(bridge_channel->chan, NULL, dtmf, 0, 0);
1736 }
1737
1738 /*! \brief Data specifying where a blind transfer is going to */
1739 struct blind_transfer_data {
1740         char exten[AST_MAX_EXTENSION];
1741         char context[AST_MAX_CONTEXT];
1742 };
1743
1744 /*!
1745  * \internal
1746  * \brief Execute after bridge actions on a channel when it leaves a bridge
1747  */
1748 static void after_bridge_move_channel(struct ast_channel *chan_bridged, void *data)
1749 {
1750         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1751         struct ast_party_connected_line connected_target;
1752         unsigned char connected_line_data[1024];
1753         int payload_size;
1754
1755         ast_party_connected_line_init(&connected_target);
1756
1757         ast_channel_lock(chan_target);
1758         ast_party_connected_line_copy(&connected_target, ast_channel_connected(chan_target));
1759         ast_channel_unlock(chan_target);
1760         ast_party_id_reset(&connected_target.priv);
1761
1762         if (ast_channel_move(chan_target, chan_bridged)) {
1763                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1764                 ast_party_connected_line_free(&connected_target);
1765                 return;
1766         }
1767
1768         /* The ast_channel_move function will end up updating the connected line information
1769          * on chan_target to the value we have here, but will not inform it. To ensure that
1770          * AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO is executed we wipe it away here. If
1771          * we don't do this then the change will be considered redundant, since the connected
1772          * line information is already there (despite the channel not being told).
1773          */
1774         ast_channel_lock(chan_target);
1775         ast_party_connected_line_free(ast_channel_connected_indicated(chan_target));
1776         ast_party_connected_line_init(ast_channel_connected_indicated(chan_target));
1777         ast_channel_unlock(chan_target);
1778
1779         if ((payload_size = ast_connected_line_build_data(connected_line_data,
1780                 sizeof(connected_line_data), &connected_target, NULL)) != -1) {
1781                 struct ast_control_read_action_payload *frame_payload;
1782                 int frame_size;
1783
1784                 frame_size = payload_size + sizeof(*frame_payload);
1785                 frame_payload = ast_alloca(frame_size);
1786                 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
1787                 frame_payload->payload_size = payload_size;
1788                 memcpy(frame_payload->payload, connected_line_data, payload_size);
1789                 ast_queue_control_data(chan_target, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
1790         }
1791
1792         /* A connected line update is queued so that if chan_target is remotely involved with
1793          * anything (such as dialing a channel) the other channel(s) will be informed of the
1794          * new channel they are involved with.
1795          */
1796         ast_channel_lock(chan_target);
1797         ast_connected_line_copy_from_caller(&connected_target, ast_channel_caller(chan_target));
1798         ast_channel_queue_connected_line_update(chan_target, &connected_target, NULL);
1799         ast_channel_unlock(chan_target);
1800
1801         ast_party_connected_line_free(&connected_target);
1802 }
1803
1804 /*!
1805  * \internal
1806  * \brief Execute logic to cleanup when after bridge fails
1807  */
1808 static void after_bridge_move_channel_fail(enum ast_bridge_after_cb_reason reason, void *data)
1809 {
1810         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1811
1812         ast_log(LOG_WARNING, "Unable to complete transfer: %s\n",
1813                 ast_bridge_after_cb_reason_string(reason));
1814         ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1815 }
1816
1817 /*!
1818  * \internal
1819  * \brief Perform a blind transfer on a channel in a bridge
1820  */
1821 static void bridge_channel_blind_transfer(struct ast_bridge_channel *bridge_channel,
1822                 struct blind_transfer_data *blind_data)
1823 {
1824         ast_async_goto(bridge_channel->chan, blind_data->context, blind_data->exten, 1);
1825         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1826 }
1827
1828 /*!
1829  * \internal
1830  * \brief Perform an attended transfer on a channel in a bridge
1831  */
1832 static void bridge_channel_attended_transfer(struct ast_bridge_channel *bridge_channel,
1833                 const char *target_chan_name)
1834 {
1835         RAII_VAR(struct ast_channel *, chan_target, NULL, ao2_cleanup);
1836         RAII_VAR(struct ast_channel *, chan_bridged, NULL, ao2_cleanup);
1837
1838         chan_target = ast_channel_get_by_name(target_chan_name);
1839         if (!chan_target) {
1840                 /* Dang, it disappeared somehow */
1841                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1842                 return;
1843         }
1844
1845         ast_bridge_channel_lock(bridge_channel);
1846         chan_bridged = bridge_channel->chan;
1847         ast_assert(chan_bridged != NULL);
1848         ao2_ref(chan_bridged, +1);
1849         ast_bridge_channel_unlock(bridge_channel);
1850
1851         if (ast_bridge_set_after_callback(chan_bridged, after_bridge_move_channel,
1852                 after_bridge_move_channel_fail, ast_channel_ref(chan_target))) {
1853                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1854
1855                 /* Release the ref we tried to pass to ast_bridge_set_after_callback(). */
1856                 ast_channel_unref(chan_target);
1857         }
1858         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1859 }
1860
1861 /*!
1862  * \internal
1863  * \brief Handle bridge channel bridge action frame.
1864  * \since 12.0.0
1865  *
1866  * \param bridge_channel Channel to execute the action on.
1867  * \param action What to do.
1868  * \param data data from the action.
1869  *
1870  * \return Nothing
1871  */
1872 static void bridge_channel_handle_action(struct ast_bridge_channel *bridge_channel,
1873         enum bridge_channel_action_type action, void *data)
1874 {
1875         switch (action) {
1876         case BRIDGE_CHANNEL_ACTION_DTMF_STREAM:
1877                 bridge_channel_suspend(bridge_channel);
1878                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1879                 bridge_channel_dtmf_stream(bridge_channel, data);
1880                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1881                 bridge_channel_unsuspend(bridge_channel);
1882                 break;
1883         case BRIDGE_CHANNEL_ACTION_TALKING_START:
1884         case BRIDGE_CHANNEL_ACTION_TALKING_STOP:
1885                 bridge_channel_talking(bridge_channel,
1886                         action == BRIDGE_CHANNEL_ACTION_TALKING_START);
1887                 break;
1888         case BRIDGE_CHANNEL_ACTION_PLAY_FILE:
1889                 bridge_channel_suspend(bridge_channel);
1890                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1891                 bridge_channel_playfile(bridge_channel, data);
1892                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1893                 bridge_channel_unsuspend(bridge_channel);
1894                 break;
1895         case BRIDGE_CHANNEL_ACTION_RUN_APP:
1896                 bridge_channel_suspend(bridge_channel);
1897                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1898                 bridge_channel_run_app(bridge_channel, data);
1899                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1900                 bridge_channel_unsuspend(bridge_channel);
1901                 break;
1902         case BRIDGE_CHANNEL_ACTION_CALLBACK:
1903                 bridge_channel_do_callback(bridge_channel, data);
1904                 break;
1905         case BRIDGE_CHANNEL_ACTION_PARK:
1906                 bridge_channel_suspend(bridge_channel);
1907                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1908                 bridge_channel_park(bridge_channel, data);
1909                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1910                 bridge_channel_unsuspend(bridge_channel);
1911                 break;
1912         case BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER:
1913                 bridge_channel_blind_transfer(bridge_channel, data);
1914                 break;
1915         case BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER:
1916                 bridge_channel_attended_transfer(bridge_channel, data);
1917                 break;
1918         default:
1919                 break;
1920         }
1921
1922         /* While invoking an action it is possible for the channel to be hung up. So
1923          * that the bridge respects this we check here and if hung up kick it out.
1924          */
1925         if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
1926                 ast_bridge_channel_kick(bridge_channel, 0);
1927         }
1928 }
1929
1930 /*!
1931  * \internal
1932  * \brief Check if a bridge should dissolve and do it.
1933  * \since 12.0.0
1934  *
1935  * \param bridge_channel Channel causing the check.
1936  *
1937  * \note On entry, bridge_channel->bridge is already locked.
1938  *
1939  * \return Nothing
1940  */
1941 static void bridge_channel_dissolve_check(struct ast_bridge_channel *bridge_channel)
1942 {
1943         struct ast_bridge *bridge = bridge_channel->bridge;
1944
1945         if (bridge->dissolved) {
1946                 return;
1947         }
1948
1949         if (!bridge->num_channels
1950                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY)) {
1951                 /* Last channel leaving the bridge turns off the lights. */
1952                 bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
1953                 return;
1954         }
1955
1956         switch (bridge_channel->state) {
1957         case BRIDGE_CHANNEL_STATE_END:
1958                 /* Do we need to dissolve the bridge because this channel hung up? */
1959                 if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)
1960                         || (bridge_channel->features->usable
1961                                 && ast_test_flag(&bridge_channel->features->feature_flags,
1962                                         AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP))) {
1963                         bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
1964                         return;
1965                 }
1966                 break;
1967         default:
1968                 break;
1969         }
1970
1971         if (bridge->num_lonely && bridge->num_lonely == bridge->num_channels) {
1972                 /*
1973                  * This will start a chain reaction where each channel leaving
1974                  * enters this function and causes the next to leave as long as
1975                  * there aren't non-lonely channels in the bridge.
1976                  */
1977                 ast_bridge_channel_leave_bridge(AST_LIST_FIRST(&bridge->channels),
1978                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE,
1979                         ast_channel_hangupcause(bridge_channel->chan));
1980         }
1981 }
1982
1983 void bridge_channel_internal_pull(struct ast_bridge_channel *bridge_channel)
1984 {
1985         struct ast_bridge *bridge = bridge_channel->bridge;
1986
1987         if (!bridge_channel->in_bridge) {
1988                 return;
1989         }
1990         bridge_channel->in_bridge = 0;
1991
1992         ast_debug(1, "Bridge %s: pulling %p(%s)\n",
1993                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1994
1995         ast_verb(3, "Channel %s left '%s' %s-bridge <%s>\n",
1996                 ast_channel_name(bridge_channel->chan),
1997                 bridge->technology->name,
1998                 bridge->v_table->name,
1999                 bridge->uniqueid);
2000
2001         if (!bridge_channel->just_joined) {
2002                 /* Tell the bridge technology we are leaving so they tear us down */
2003                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology\n",
2004                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
2005                         bridge->technology->name);
2006                 if (bridge->technology->leave) {
2007                         bridge->technology->leave(bridge, bridge_channel);
2008                 }
2009         }
2010
2011         /* Remove channel from the bridge */
2012         if (!bridge_channel->suspended) {
2013                 --bridge->num_active;
2014         }
2015         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
2016                 --bridge->num_lonely;
2017         }
2018         --bridge->num_channels;
2019         AST_LIST_REMOVE(&bridge->channels, bridge_channel, entry);
2020
2021         bridge_channel_dissolve_check(bridge_channel);
2022         bridge->v_table->pull(bridge, bridge_channel);
2023
2024         ast_bridge_channel_clear_roles(bridge_channel);
2025
2026         /* If we are not going to be hung up after leaving a bridge, and we were an
2027          * outgoing channel, clear the outgoing flag.
2028          */
2029         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING)
2030             && (ast_channel_is_leaving_bridge(bridge_channel->chan)
2031                 || bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT)) {
2032                 ast_debug(2, "Channel %s will survive this bridge; clearing outgoing (dialed) flag\n", ast_channel_name(bridge_channel->chan));
2033                 ast_clear_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING);
2034         }
2035
2036         bridge->reconfigured = 1;
2037         ast_bridge_publish_leave(bridge, bridge_channel->chan);
2038 }
2039
2040 int bridge_channel_internal_push(struct ast_bridge_channel *bridge_channel)
2041 {
2042         struct ast_bridge *bridge = bridge_channel->bridge;
2043         struct ast_bridge_channel *swap;
2044
2045         ast_assert(!bridge_channel->in_bridge);
2046
2047         swap = bridge_find_channel(bridge, bridge_channel->swap);
2048         bridge_channel->swap = NULL;
2049
2050         if (swap) {
2051                 ast_debug(1, "Bridge %s: pushing %p(%s) by swapping with %p(%s)\n",
2052                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
2053                         swap, ast_channel_name(swap->chan));
2054         } else {
2055                 ast_debug(1, "Bridge %s: pushing %p(%s)\n",
2056                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
2057         }
2058
2059         /* Add channel to the bridge */
2060         if (bridge->dissolved
2061                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2062                 || (swap && swap->state != BRIDGE_CHANNEL_STATE_WAIT)
2063                 || bridge->v_table->push(bridge, bridge_channel, swap)
2064                 || ast_bridge_channel_establish_roles(bridge_channel)) {
2065                 ast_debug(1, "Bridge %s: pushing %p(%s) into bridge failed\n",
2066                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
2067                 return -1;
2068         }
2069
2070         if (swap) {
2071                 int dissolve = ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY);
2072
2073                 /* This flag is cleared so the act of this channel leaving does not cause it to dissolve if need be */
2074                 ast_clear_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY);
2075
2076                 ast_bridge_channel_leave_bridge(swap, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, 0);
2077                 bridge_channel_internal_pull(swap);
2078
2079                 ast_set2_flag(&bridge->feature_flags, dissolve, AST_BRIDGE_FLAG_DISSOLVE_EMPTY);
2080         }
2081
2082         bridge_channel->in_bridge = 1;
2083         bridge_channel->just_joined = 1;
2084         AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
2085         ++bridge->num_channels;
2086         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
2087                 ++bridge->num_lonely;
2088         }
2089         if (!bridge_channel->suspended) {
2090                 ++bridge->num_active;
2091         }
2092
2093         ast_verb(3, "Channel %s %s%s%s '%s' %s-bridge <%s>\n",
2094                 ast_channel_name(bridge_channel->chan),
2095                 swap ? "swapped with " : "joined",
2096                 swap ? ast_channel_name(swap->chan) : "",
2097                 swap ? " into" : "",
2098                 bridge->technology->name,
2099                 bridge->v_table->name,
2100                 bridge->uniqueid);
2101
2102         ast_bridge_publish_enter(bridge, bridge_channel->chan, swap ? swap->chan : NULL);
2103
2104         /* Clear any BLINDTRANSFER and ATTENDEDTRANSFER since the transfer has completed. */
2105         pbx_builtin_setvar_helper(bridge_channel->chan, "BLINDTRANSFER", NULL);
2106         pbx_builtin_setvar_helper(bridge_channel->chan, "ATTENDEDTRANSFER", NULL);
2107
2108         /* Wake up the bridge channel thread to reevaluate any interval timers. */
2109         ast_queue_frame(bridge_channel->chan, &ast_null_frame);
2110
2111         bridge->reconfigured = 1;
2112         return 0;
2113 }
2114
2115 /*!
2116  * \internal
2117  * \brief Handle bridge channel control frame action.
2118  * \since 12.0.0
2119  *
2120  * \param bridge_channel Channel to execute the control frame action on.
2121  * \param fr Control frame to handle.
2122  *
2123  * \return Nothing
2124  */
2125 static void bridge_channel_handle_control(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
2126 {
2127         struct ast_channel *chan;
2128         struct ast_option_header *aoh;
2129         int is_caller;
2130
2131         chan = bridge_channel->chan;
2132         switch (fr->subclass.integer) {
2133         case AST_CONTROL_REDIRECTING:
2134                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2135                 if (ast_channel_redirecting_sub(NULL, chan, fr, 1) &&
2136                         ast_channel_redirecting_macro(NULL, chan, fr, is_caller, 1)) {
2137                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2138                 }
2139                 break;
2140         case AST_CONTROL_CONNECTED_LINE:
2141                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2142                 if (ast_channel_connected_line_sub(NULL, chan, fr, 1) &&
2143                         ast_channel_connected_line_macro(NULL, chan, fr, is_caller, 1)) {
2144                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2145                 }
2146                 break;
2147         case AST_CONTROL_OPTION:
2148                 /*
2149                  * Forward option Requests, but only ones we know are safe These
2150                  * are ONLY sent by chan_iax2 and I'm not convinced that they
2151                  * are useful. I haven't deleted them entirely because I just am
2152                  * not sure of the ramifications of removing them.
2153                  */
2154                 aoh = fr->data.ptr;
2155                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
2156                         switch (ntohs(aoh->option)) {
2157                         case AST_OPTION_TONE_VERIFY:
2158                         case AST_OPTION_TDD:
2159                         case AST_OPTION_RELAXDTMF:
2160                         case AST_OPTION_AUDIO_MODE:
2161                         case AST_OPTION_DIGIT_DETECT:
2162                         case AST_OPTION_FAX_DETECT:
2163                                 ast_channel_setoption(chan, ntohs(aoh->option), aoh->data,
2164                                         fr->datalen - sizeof(*aoh), 0);
2165                                 break;
2166                         default:
2167                                 break;
2168                         }
2169                 }
2170                 break;
2171         case AST_CONTROL_ANSWER:
2172                 if (ast_channel_state(chan) != AST_STATE_UP) {
2173                         ast_answer(chan);
2174                 } else {
2175                         ast_indicate(chan, -1);
2176                 }
2177                 break;
2178         case AST_CONTROL_MASQUERADE_NOTIFY:
2179                 /* Should never happen. */
2180                 ast_assert(0);
2181                 break;
2182         default:
2183                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2184                 break;
2185         }
2186 }
2187
2188 /*!
2189  * \internal
2190  * \param bridge_channel Channel to read wr_queue alert pipe.
2191  *
2192  * \return Nothing
2193  */
2194 static void bridge_channel_read_wr_queue_alert(struct ast_bridge_channel *bridge_channel)
2195 {
2196         char nudge;
2197
2198         if (read(bridge_channel->alert_pipe[0], &nudge, sizeof(nudge)) < 0) {
2199                 if (errno != EINTR && errno != EAGAIN) {
2200                         ast_log(LOG_WARNING, "read() failed for alert pipe on %p(%s): %s\n",
2201                                 bridge_channel, ast_channel_name(bridge_channel->chan),
2202                                 strerror(errno));
2203                 }
2204         }
2205 }
2206
2207 /*!
2208  * \internal
2209  * \brief Handle bridge channel write frame to channel.
2210  * \since 12.0.0
2211  *
2212  * \param bridge_channel Channel to write outgoing frame.
2213  *
2214  * \return Nothing
2215  */
2216 static void bridge_channel_handle_write(struct ast_bridge_channel *bridge_channel)
2217 {
2218         struct ast_frame *fr;
2219         struct sync_payload *sync_payload;
2220
2221         ast_bridge_channel_lock(bridge_channel);
2222
2223         /* It's not good to have unbalanced frames and alert_pipe alerts. */
2224         ast_assert(!AST_LIST_EMPTY(&bridge_channel->wr_queue));
2225         if (AST_LIST_EMPTY(&bridge_channel->wr_queue)) {
2226                 /* No frame, flush the alert pipe of excess alerts. */
2227                 ast_log(LOG_WARNING, "Weird.  No frame from bridge for %s to process?\n",
2228                         ast_channel_name(bridge_channel->chan));
2229                 bridge_channel_read_wr_queue_alert(bridge_channel);
2230                 ast_bridge_channel_unlock(bridge_channel);
2231                 return;
2232         }
2233
2234         AST_LIST_TRAVERSE_SAFE_BEGIN(&bridge_channel->wr_queue, fr, frame_list) {
2235                 if (bridge_channel->dtmf_hook_state.collected[0]) {
2236                         switch (fr->frametype) {
2237                         case AST_FRAME_BRIDGE_ACTION:
2238                         case AST_FRAME_BRIDGE_ACTION_SYNC:
2239                                 /* Defer processing these frames while DTMF is collected. */
2240                                 continue;
2241                         default:
2242                                 break;
2243                         }
2244                 }
2245                 bridge_channel_read_wr_queue_alert(bridge_channel);
2246                 AST_LIST_REMOVE_CURRENT(frame_list);
2247                 break;
2248         }
2249         AST_LIST_TRAVERSE_SAFE_END;
2250
2251         ast_bridge_channel_unlock(bridge_channel);
2252         if (!fr) {
2253                 /*
2254                  * Wait some to reduce CPU usage from a tight loop
2255                  * without any wait because we only have deferred
2256                  * frames in the wr_queue.
2257                  */
2258                 usleep(1);
2259                 return;
2260         }
2261
2262         switch (fr->frametype) {
2263         case AST_FRAME_BRIDGE_ACTION:
2264                 bridge_channel_handle_action(bridge_channel, fr->subclass.integer, fr->data.ptr);
2265                 break;
2266         case AST_FRAME_BRIDGE_ACTION_SYNC:
2267                 sync_payload = fr->data.ptr;
2268                 bridge_channel_handle_action(bridge_channel, fr->subclass.integer, sync_payload->data);
2269                 break;
2270         case AST_FRAME_CONTROL:
2271                 bridge_channel_handle_control(bridge_channel, fr);
2272                 break;
2273         case AST_FRAME_NULL:
2274                 break;
2275         default:
2276                 /* Write the frame to the channel. */
2277                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_SIMPLE;
2278                 ast_write(bridge_channel->chan, fr);
2279                 break;
2280         }
2281         bridge_frame_free(fr);
2282 }
2283
2284 /*! \brief Internal function to handle DTMF from a channel */
2285 static struct ast_frame *bridge_handle_dtmf(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
2286 {
2287         struct ast_bridge_features *features = bridge_channel->features;
2288         struct ast_bridge_hook_dtmf *hook = NULL;
2289         char dtmf[2];
2290
2291         /*
2292          * See if we are already matching a DTMF feature hook sequence or
2293          * if this DTMF matches the beginning of any DTMF feature hooks.
2294          */
2295         dtmf[0] = frame->subclass.integer;
2296         dtmf[1] = '\0';
2297         if (bridge_channel->dtmf_hook_state.collected[0]
2298                 || (hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_SEARCH_PARTIAL_KEY))) {
2299                 enum ast_frame_type frametype = frame->frametype;
2300
2301                 bridge_frame_free(frame);
2302                 frame = NULL;
2303
2304                 ao2_cleanup(hook);
2305
2306                 switch (frametype) {
2307                 case AST_FRAME_DTMF_BEGIN:
2308                         /* Just eat the frame. */
2309                         break;
2310                 case AST_FRAME_DTMF_END:
2311                         ast_bridge_channel_feature_digit(bridge_channel, dtmf[0]);
2312                         break;
2313                 default:
2314                         /* Unexpected frame type. */
2315                         ast_assert(0);
2316                         break;
2317                 }
2318 #ifdef TEST_FRAMEWORK
2319         } else if (frame->frametype == AST_FRAME_DTMF_END) {
2320                 /* Only transmit this event on DTMF end or else every DTMF
2321                  * press will result in the event being broadcast twice
2322                  */
2323                 ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
2324 #endif
2325         }
2326
2327         return frame;
2328 }
2329
2330
2331 /*!
2332  * \internal
2333  * \brief Feed notification that a frame is waiting on a channel into the bridging core
2334  *
2335  * \param bridge_channel Bridge channel the notification was received on
2336  */
2337 static void bridge_handle_trip(struct ast_bridge_channel *bridge_channel)
2338 {
2339         struct ast_frame *frame;
2340
2341         if (bridge_channel->features->mute) {
2342                 frame = ast_read_noaudio(bridge_channel->chan);
2343         } else {
2344                 frame = ast_read(bridge_channel->chan);
2345         }
2346
2347         if (!frame) {
2348                 ast_bridge_channel_kick(bridge_channel, 0);
2349                 return;
2350         }
2351         switch (frame->frametype) {
2352         case AST_FRAME_CONTROL:
2353                 switch (frame->subclass.integer) {
2354                 case AST_CONTROL_HANGUP:
2355                         ast_bridge_channel_kick(bridge_channel, 0);
2356                         bridge_frame_free(frame);
2357                         return;
2358                 default:
2359                         break;
2360                 }
2361                 break;
2362         case AST_FRAME_DTMF_BEGIN:
2363         case AST_FRAME_DTMF_END:
2364                 frame = bridge_handle_dtmf(bridge_channel, frame);
2365                 if (!frame) {
2366                         return;
2367                 }
2368                 if (!bridge_channel->features->dtmf_passthrough) {
2369                         bridge_frame_free(frame);
2370                         return;
2371                 }
2372                 break;
2373         default:
2374                 break;
2375         }
2376
2377         /* Simply write the frame out to the bridge technology. */
2378         bridge_channel_write_frame(bridge_channel, frame);
2379         bridge_frame_free(frame);
2380 }
2381
2382 /*!
2383  * \internal
2384  * \brief Determine how long till the next timer interval.
2385  * \since 12.0.0
2386  *
2387  * \param bridge_channel Channel to determine how long can wait.
2388  *
2389  * \retval ms Number of milliseconds to wait.
2390  * \retval -1 to wait forever.
2391  */
2392 static int bridge_channel_next_interval(struct ast_bridge_channel *bridge_channel)
2393 {
2394         struct ast_heap *interval_hooks = bridge_channel->features->interval_hooks;
2395         struct ast_bridge_hook_timer *hook;
2396         int ms;
2397
2398         ast_heap_wrlock(interval_hooks);
2399         hook = ast_heap_peek(interval_hooks, 1);
2400         if (hook) {
2401                 ms = ast_tvdiff_ms(hook->timer.trip_time, ast_tvnow());
2402                 if (ms < 0) {
2403                         /* Expire immediately.  An interval hook is ready to run. */
2404                         ms = 0;
2405                 }
2406         } else {
2407                 /* No hook so wait forever. */
2408                 ms = -1;
2409         }
2410         ast_heap_unlock(interval_hooks);
2411
2412         return ms;
2413 }
2414
2415 /*!
2416  * \internal
2417  * \brief Determine how long till the DTMF interdigit timeout.
2418  * \since 12.8.0
2419  *
2420  * \param bridge_channel Channel to determine how long can wait.
2421  *
2422  * \retval ms Number of milliseconds to wait.
2423  * \retval -1 to wait forever.
2424  */
2425 static int bridge_channel_feature_timeout(struct ast_bridge_channel *bridge_channel)
2426 {
2427         int ms;
2428
2429         if (bridge_channel->dtmf_hook_state.collected[0]) {
2430                 ms = ast_tvdiff_ms(bridge_channel->dtmf_hook_state.interdigit_timeout,
2431                         ast_tvnow());
2432                 if (ms < 0) {
2433                         /* Expire immediately. */
2434                         ms = 0;
2435                 }
2436         } else {
2437                 /* Timer is not active so wait forever. */
2438                 ms = -1;
2439         }
2440
2441         return ms;
2442 }
2443
2444 /*!
2445  * \internal
2446  * \brief Determine how long till a timeout.
2447  * \since 12.8.0
2448  *
2449  * \param bridge_channel Channel to determine how long can wait.
2450  *
2451  * \retval ms Number of milliseconds to wait.
2452  * \retval -1 to wait forever.
2453  */
2454 static int bridge_channel_next_timeout(struct ast_bridge_channel *bridge_channel)
2455 {
2456         int ms_interval;
2457         int ms;
2458
2459         ms_interval = bridge_channel_next_interval(bridge_channel);
2460         ms = bridge_channel_feature_timeout(bridge_channel);
2461         if (ms < 0 || (0 <= ms_interval && ms_interval < ms)) {
2462                 /* Interval hook timeout is next. */
2463                 ms = ms_interval;
2464         }
2465
2466         return ms;
2467 }
2468
2469 /*!
2470  * \internal
2471  * \brief Wait for something to happen on the bridge channel and handle it.
2472  * \since 12.0.0
2473  *
2474  * \param bridge_channel Channel to wait.
2475  *
2476  * \note Each channel does writing/reading in their own thread.
2477  *
2478  * \return Nothing
2479  */
2480 static void bridge_channel_wait(struct ast_bridge_channel *bridge_channel)
2481 {
2482         int ms;
2483         int outfd;
2484         struct ast_channel *chan;
2485
2486         /* Wait for data to either come from the channel or us to be signaled */
2487         ast_bridge_channel_lock(bridge_channel);
2488         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2489         } else if (bridge_channel->suspended) {
2490 /* XXX ASTERISK-21271 the external party use of suspended will go away as will these references because this is the bridge channel thread */
2491                 ast_debug(1, "Bridge %s: %p(%s) is going into a signal wait\n",
2492                         bridge_channel->bridge->uniqueid, bridge_channel,
2493                         ast_channel_name(bridge_channel->chan));
2494                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
2495         } else {
2496                 ast_bridge_channel_unlock(bridge_channel);
2497                 outfd = -1;
2498                 ms = bridge_channel_next_timeout(bridge_channel);
2499                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1,
2500                         &bridge_channel->alert_pipe[0], 1, NULL, &outfd, &ms);
2501                 if (ast_channel_unbridged(bridge_channel->chan)) {
2502                         ast_channel_set_unbridged(bridge_channel->chan, 0);
2503                         ast_bridge_channel_lock_bridge(bridge_channel);
2504                         bridge_channel->bridge->reconfigured = 1;
2505                         bridge_reconfigured(bridge_channel->bridge, 0);
2506                         ast_bridge_unlock(bridge_channel->bridge);
2507                 }
2508                 ast_bridge_channel_lock(bridge_channel);
2509                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_FRAME;
2510                 ast_bridge_channel_unlock(bridge_channel);
2511                 if (!bridge_channel->suspended
2512                         && bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2513                         if (chan) {
2514                                 bridge_handle_trip(bridge_channel);
2515                         } else if (ms == 0) {
2516                                 /* An interdigit timeout or interval expired. */
2517                                 bridge_channel_handle_feature_timeout(bridge_channel);
2518                                 bridge_channel_handle_interval(bridge_channel);
2519                         } else if (-1 < outfd) {
2520                                 /*
2521                                  * Must do this after checking timeouts or may have
2522                                  * an infinite loop due to deferring write queue
2523                                  * actions while trying to match DTMF feature hooks.
2524                                  */
2525                                 bridge_channel_handle_write(bridge_channel);
2526                         }
2527                 }
2528                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_IDLE;
2529                 return;
2530         }
2531         ast_bridge_channel_unlock(bridge_channel);
2532 }
2533
2534 /*!
2535  * \internal
2536  * \brief Handle bridge channel join/leave event.
2537  * \since 12.0.0
2538  *
2539  * \param bridge_channel Which channel is involved.
2540  * \param type Specified join/leave event.
2541  *
2542  * \return Nothing
2543  */
2544 static void bridge_channel_event_join_leave(struct ast_bridge_channel *bridge_channel, enum ast_bridge_hook_type type)
2545 {
2546         struct ast_bridge_features *features = bridge_channel->features;
2547         struct ast_bridge_hook *hook;
2548         struct ao2_iterator iter;
2549
2550         /* Run the specified hooks. */
2551         iter = ao2_iterator_init(features->other_hooks, 0);
2552         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
2553                 if (hook->type == type) {
2554                         break;
2555                 }
2556         }
2557         if (hook) {
2558                 /* Found the first specified hook to run. */
2559                 bridge_channel_suspend(bridge_channel);
2560                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2561                 do {
2562                         if (hook->type == type) {
2563                                 hook->callback(bridge_channel, hook->hook_pvt);
2564                                 ao2_unlink(features->other_hooks, hook);
2565                         }
2566                         ao2_ref(hook, -1);
2567                 } while ((hook = ao2_iterator_next(&iter)));
2568                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2569                 bridge_channel_unsuspend(bridge_channel);
2570         }
2571         ao2_iterator_destroy(&iter);
2572 }
2573
2574 void bridge_channel_internal_wait(struct bridge_channel_internal_cond *cond)
2575 {
2576         ast_mutex_lock(&cond->lock);
2577         while (!cond->done) {
2578                 ast_cond_wait(&cond->cond, &cond->lock);
2579         }
2580         ast_mutex_unlock(&cond->lock);
2581 }
2582
2583 void bridge_channel_internal_signal(struct bridge_channel_internal_cond *cond)
2584 {
2585         if (cond) {
2586                 ast_mutex_lock(&cond->lock);
2587                 cond->done = 1;
2588                 ast_cond_signal(&cond->cond);
2589                 ast_mutex_unlock(&cond->lock);
2590         }
2591 }
2592
2593 int bridge_channel_internal_join(struct ast_bridge_channel *bridge_channel,
2594                                  struct bridge_channel_internal_cond *cond)
2595 {
2596         int res = 0;
2597         struct ast_bridge_features *channel_features;
2598         struct ast_channel *swap;
2599
2600         ast_debug(1, "Bridge %s: %p(%s) is joining\n",
2601                 bridge_channel->bridge->uniqueid,
2602                 bridge_channel, ast_channel_name(bridge_channel->chan));
2603
2604         /*
2605          * Directly locking the bridge is safe here because nobody else
2606          * knows about this bridge_channel yet.
2607          */
2608         ast_bridge_lock(bridge_channel->bridge);
2609
2610         ast_channel_lock(bridge_channel->chan);
2611
2612         bridge_channel->read_format = ao2_bump(ast_channel_readformat(bridge_channel->chan));
2613         bridge_channel->write_format = ao2_bump(ast_channel_writeformat(bridge_channel->chan));
2614
2615         /* Make sure we're still good to be put into a bridge */
2616         if (ast_channel_internal_bridge(bridge_channel->chan)
2617                 || ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_ZOMBIE)) {
2618                 ast_channel_unlock(bridge_channel->chan);
2619                 ast_bridge_unlock(bridge_channel->bridge);
2620                 ast_debug(1, "Bridge %s: %p(%s) failed to join Bridge\n",
2621                         bridge_channel->bridge->uniqueid,
2622                         bridge_channel,
2623                         ast_channel_name(bridge_channel->chan));
2624                 bridge_channel_internal_signal(cond);
2625                 return -1;
2626         }
2627         ast_channel_internal_bridge_set(bridge_channel->chan, bridge_channel->bridge);
2628
2629         /* Attach features requested by the channel */
2630         channel_features = ast_channel_feature_hooks_get(bridge_channel->chan);
2631         if (channel_features) {
2632                 ast_bridge_features_merge(bridge_channel->features, channel_features);
2633         }
2634         ast_channel_unlock(bridge_channel->chan);
2635
2636         /* Add the jitterbuffer if the channel requires it */
2637         ast_jb_enable_for_channel(bridge_channel->chan);
2638
2639         if (!bridge_channel->bridge->callid) {
2640                 bridge_channel->bridge->callid = ast_read_threadstorage_callid();
2641         }
2642
2643         /* Take the swap channel ref from the bridge_channel struct. */
2644         swap = bridge_channel->swap;
2645
2646         if (bridge_channel_internal_push(bridge_channel)) {
2647                 int cause = bridge_channel->bridge->cause;
2648
2649                 ast_bridge_unlock(bridge_channel->bridge);
2650                 ast_bridge_channel_kick(bridge_channel, cause);
2651                 ast_bridge_channel_lock_bridge(bridge_channel);
2652                 ast_bridge_features_remove(bridge_channel->features,
2653                         AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2654                 bridge_channel_dissolve_check(bridge_channel);
2655                 res = -1;
2656         }
2657         bridge_reconfigured(bridge_channel->bridge, !bridge_channel->inhibit_colp);
2658
2659         bridge_channel_internal_signal(cond);
2660
2661         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2662                 /*
2663                  * Indicate a source change since this channel is entering the
2664                  * bridge system only if the bridge technology is not MULTIMIX
2665                  * capable.  The MULTIMIX technology has already done it.
2666                  */
2667                 if (!(bridge_channel->bridge->technology->capabilities
2668                         & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
2669                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2670                 }
2671
2672                 ast_bridge_unlock(bridge_channel->bridge);
2673
2674                 /* Must release any swap ref after unlocking the bridge. */
2675                 ao2_t_cleanup(swap, "Bridge push with swap successful");
2676                 swap = NULL;
2677
2678                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_JOIN);
2679
2680                 while (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2681                         /* Wait for something to do. */
2682                         bridge_channel_wait(bridge_channel);
2683                 }
2684
2685                 /* Force a timeout on any accumulated DTMF hook digits. */
2686                 ast_bridge_channel_feature_digit(bridge_channel, 0);
2687
2688                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_LEAVE);
2689                 ast_bridge_channel_lock_bridge(bridge_channel);
2690         }
2691
2692         bridge_channel_internal_pull(bridge_channel);
2693         bridge_channel_settle_owed_events(bridge_channel->bridge, bridge_channel);
2694         bridge_reconfigured(bridge_channel->bridge, 1);
2695
2696         ast_bridge_unlock(bridge_channel->bridge);
2697
2698         /* Must release any swap ref after unlocking the bridge. */
2699         ao2_t_cleanup(swap, "Bridge push with swap failed or exited immediately");
2700
2701         /* Complete any active hold before exiting the bridge. */
2702         if (ast_channel_hold_state(bridge_channel->chan) == AST_CONTROL_HOLD) {
2703                 ast_debug(1, "Channel %s simulating UNHOLD for bridge end.\n",
2704                         ast_channel_name(bridge_channel->chan));
2705                 ast_indicate(bridge_channel->chan, AST_CONTROL_UNHOLD);
2706         }
2707
2708         /* Complete any partial DTMF digit before exiting the bridge. */
2709         if (ast_channel_sending_dtmf_digit(bridge_channel->chan)) {
2710                 ast_channel_end_dtmf(bridge_channel->chan,
2711                         ast_channel_sending_dtmf_digit(bridge_channel->chan),
2712                         ast_channel_sending_dtmf_tv(bridge_channel->chan), "bridge end");
2713         }
2714
2715         /* Indicate a source change since this channel is leaving the bridge system. */
2716         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2717
2718         /*
2719          * Wait for any dual redirect to complete.
2720          *
2721          * Must be done while "still in the bridge" for ast_async_goto()
2722          * to work right.
2723          */
2724         while (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT)) {
2725                 sched_yield();
2726         }
2727         ast_channel_lock(bridge_channel->chan);
2728         ast_channel_internal_bridge_set(bridge_channel->chan, NULL);
2729         ast_channel_unlock(bridge_channel->chan);
2730
2731         ast_bridge_channel_restore_formats(bridge_channel);
2732
2733         return res;
2734 }
2735
2736 int bridge_channel_internal_queue_blind_transfer(struct ast_channel *transferee,
2737                 const char *exten, const char *context,
2738                 transfer_channel_cb new_channel_cb, void *user_data)
2739 {
2740         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2741         struct blind_transfer_data blind_data;
2742
2743         ast_channel_lock(transferee);
2744         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2745         ast_channel_unlock(transferee);
2746
2747         if (!transferee_bridge_channel) {
2748                 return -1;
2749         }
2750
2751         if (new_channel_cb) {
2752                 new_channel_cb(transferee, user_data, AST_BRIDGE_TRANSFER_SINGLE_PARTY);
2753         }
2754
2755         ast_copy_string(blind_data.exten, exten, sizeof(blind_data.exten));
2756         ast_copy_string(blind_data.context, context, sizeof(blind_data.context));
2757
2758         return bridge_channel_queue_action_data(transferee_bridge_channel,
2759                 BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER, &blind_data, sizeof(blind_data));
2760 }
2761
2762 int bridge_channel_internal_queue_attended_transfer(struct ast_channel *transferee,
2763                 struct ast_channel *unbridged_chan)
2764 {
2765         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2766         char unbridged_chan_name[AST_CHANNEL_NAME];
2767
2768         ast_channel_lock(transferee);
2769         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2770         ast_channel_unlock(transferee);
2771
2772         if (!transferee_bridge_channel) {
2773                 return -1;
2774         }
2775
2776         ast_copy_string(unbridged_chan_name, ast_channel_name(unbridged_chan),
2777                 sizeof(unbridged_chan_name));
2778
2779         return bridge_channel_queue_action_data(transferee_bridge_channel,
2780                 BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER, unbridged_chan_name,
2781                 sizeof(unbridged_chan_name));
2782 }
2783
2784 int bridge_channel_internal_allows_optimization(struct ast_bridge_channel *bridge_channel)
2785 {
2786         return bridge_channel->in_bridge
2787                 && AST_LIST_EMPTY(&bridge_channel->wr_queue);
2788 }
2789
2790 /*!
2791  * \internal
2792  * \brief Close a pipe.
2793  * \since 12.0.0
2794  *
2795  * \param my_pipe What to close.
2796  *
2797  * \return Nothing
2798  */
2799 static void pipe_close(int *my_pipe)
2800 {
2801         if (my_pipe[0] > -1) {
2802                 close(my_pipe[0]);
2803                 my_pipe[0] = -1;
2804         }
2805         if (my_pipe[1] > -1) {
2806                 close(my_pipe[1]);
2807                 my_pipe[1] = -1;
2808         }
2809 }
2810
2811 /*!
2812  * \internal
2813  * \brief Initialize a pipe as non-blocking.
2814  * \since 12.0.0
2815  *
2816  * \param my_pipe What to initialize.
2817  *
2818  * \retval 0 on success.
2819  * \retval -1 on error.
2820  */
2821 static int pipe_init_nonblock(int *my_pipe)
2822 {
2823         int flags;
2824
2825         my_pipe[0] = -1;
2826         my_pipe[1] = -1;
2827         if (pipe(my_pipe)) {
2828                 ast_log(LOG_WARNING, "Can't create pipe! Try increasing max file descriptors with ulimit -n\n");
2829                 return -1;
2830         }
2831         flags = fcntl(my_pipe[0], F_GETFL);
2832         if (fcntl(my_pipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2833                 ast_log(LOG_WARNING, "Unable to set read pipe nonblocking! (%d: %s)\n",
2834                         errno, strerror(errno));
2835                 return -1;
2836         }
2837         flags = fcntl(my_pipe[1], F_GETFL);
2838         if (fcntl(my_pipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
2839                 ast_log(LOG_WARNING, "Unable to set write pipe nonblocking! (%d: %s)\n",
2840                         errno, strerror(errno));
2841                 return -1;
2842         }
2843         return 0;
2844 }
2845
2846 /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
2847 static void bridge_channel_destroy(void *obj)
2848 {
2849         struct ast_bridge_channel *bridge_channel = obj;
2850         struct ast_frame *fr;
2851
2852         if (bridge_channel->callid) {
2853                 bridge_channel->callid = 0;
2854         }
2855
2856         if (bridge_channel->bridge) {
2857                 ao2_ref(bridge_channel->bridge, -1);
2858                 bridge_channel->bridge = NULL;
2859         }
2860
2861         /* Flush any unhandled wr_queue frames. */
2862         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list))) {
2863                 bridge_frame_free(fr);
2864         }
2865         pipe_close(bridge_channel->alert_pipe);
2866
2867         ast_cond_destroy(&bridge_channel->cond);
2868
2869         ao2_cleanup(bridge_channel->write_format);
2870         ao2_cleanup(bridge_channel->read_format);
2871 }
2872
2873 struct ast_bridge_channel *bridge_channel_internal_alloc(struct ast_bridge *bridge)
2874 {
2875         struct ast_bridge_channel *bridge_channel;
2876
2877         bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
2878         if (!bridge_channel) {
2879                 return NULL;
2880         }
2881         ast_cond_init(&bridge_channel->cond, NULL);
2882         if (pipe_init_nonblock(bridge_channel->alert_pipe)) {
2883                 ao2_ref(bridge_channel, -1);
2884                 return NULL;
2885         }
2886         if (bridge) {
2887                 bridge_channel->bridge = bridge;
2888                 ao2_ref(bridge_channel->bridge, +1);
2889         }
2890
2891         return bridge_channel;
2892 }