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