d5d17ae9eed3b17bbd758304162455a35a5e0962
[asterisk/asterisk.git] / main / bridging.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 Channel Bridging API
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  */
25
26 /*** MODULEINFO
27         <support_level>core</support_level>
28  ***/
29
30 #include "asterisk.h"
31
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33
34 #include <signal.h>
35
36 #include "asterisk/logger.h"
37 #include "asterisk/channel.h"
38 #include "asterisk/options.h"
39 #include "asterisk/utils.h"
40 #include "asterisk/lock.h"
41 #include "asterisk/linkedlists.h"
42 #include "asterisk/bridging.h"
43 #include "asterisk/bridging_basic.h"
44 #include "asterisk/bridging_technology.h"
45 #include "asterisk/stasis_bridging.h"
46 #include "asterisk/stasis_channels.h"
47 #include "asterisk/app.h"
48 #include "asterisk/file.h"
49 #include "asterisk/module.h"
50 #include "asterisk/astobj2.h"
51 #include "asterisk/pbx.h"
52 #include "asterisk/test.h"
53 #include "asterisk/_private.h"
54
55 #include "asterisk/heap.h"
56 #include "asterisk/say.h"
57 #include "asterisk/timing.h"
58 #include "asterisk/stringfields.h"
59 #include "asterisk/musiconhold.h"
60 #include "asterisk/features.h"
61 #include "asterisk/cli.h"
62 #include "asterisk/parking.h"
63 #include "asterisk/core_local.h"
64 #include "asterisk/features_config.h"
65
66 /*! All bridges container. */
67 static struct ao2_container *bridges;
68
69 static AST_RWLIST_HEAD_STATIC(bridge_technologies, ast_bridge_technology);
70
71 /* Initial starting point for the bridge array of channels */
72 #define BRIDGE_ARRAY_START 128
73
74 /* Grow rate of bridge array of channels */
75 #define BRIDGE_ARRAY_GROW 32
76
77 static void cleanup_video_mode(struct ast_bridge *bridge);
78 static int bridge_make_compatible(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel);
79 static void bridge_features_remove(struct ast_bridge_features *features, enum ast_bridge_hook_remove_flags remove_flags);
80
81 /*! Default DTMF keys for built in features */
82 static char builtin_features_dtmf[AST_BRIDGE_BUILTIN_END][MAXIMUM_DTMF_FEATURE_STRING];
83
84 /*! Function handlers for the built in features */
85 static void *builtin_features_handlers[AST_BRIDGE_BUILTIN_END];
86
87 /*! Function handlers for built in interval features */
88 static ast_bridge_builtin_set_limits_fn builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_END];
89
90 /*! Bridge manager service request */
91 struct bridge_manager_request {
92         /*! List of bridge service requests. */
93         AST_LIST_ENTRY(bridge_manager_request) node;
94         /*! Refed bridge requesting service. */
95         struct ast_bridge *bridge;
96 };
97
98 struct bridge_manager_controller {
99         /*! Condition, used to wake up the bridge manager thread. */
100         ast_cond_t cond;
101         /*! Queue of bridge service requests. */
102         AST_LIST_HEAD_NOLOCK(, bridge_manager_request) service_requests;
103         /*! Manager thread */
104         pthread_t thread;
105         /*! TRUE if the manager needs to stop. */
106         unsigned int stop:1;
107 };
108
109 /*! Bridge manager controller. */
110 static struct bridge_manager_controller *bridge_manager;
111
112 /*!
113  * \internal
114  * \brief Request service for a bridge from the bridge manager.
115  * \since 12.0.0
116  *
117  * \param bridge Requesting service.
118  *
119  * \return Nothing
120  */
121 static void bridge_manager_service_req(struct ast_bridge *bridge)
122 {
123         struct bridge_manager_request *request;
124
125         ao2_lock(bridge_manager);
126         if (bridge_manager->stop) {
127                 ao2_unlock(bridge_manager);
128                 return;
129         }
130
131         /* Create the service request. */
132         request = ast_calloc(1, sizeof(*request));
133         if (!request) {
134                 /* Well. This isn't good. */
135                 ao2_unlock(bridge_manager);
136                 return;
137         }
138         ao2_ref(bridge, +1);
139         request->bridge = bridge;
140
141         /* Put request into the queue and wake the bridge manager. */
142         AST_LIST_INSERT_TAIL(&bridge_manager->service_requests, request, node);
143         ast_cond_signal(&bridge_manager->cond);
144         ao2_unlock(bridge_manager);
145 }
146
147 int __ast_bridge_technology_register(struct ast_bridge_technology *technology, struct ast_module *module)
148 {
149         struct ast_bridge_technology *current;
150
151         /* Perform a sanity check to make sure the bridge technology conforms to our needed requirements */
152         if (ast_strlen_zero(technology->name)
153                 || !technology->capabilities
154                 || !technology->write) {
155                 ast_log(LOG_WARNING, "Bridge technology %s failed registration sanity check.\n",
156                         technology->name);
157                 return -1;
158         }
159
160         AST_RWLIST_WRLOCK(&bridge_technologies);
161
162         /* Look for duplicate bridge technology already using this name, or already registered */
163         AST_RWLIST_TRAVERSE(&bridge_technologies, current, entry) {
164                 if ((!strcasecmp(current->name, technology->name)) || (current == technology)) {
165                         ast_log(LOG_WARNING, "A bridge technology of %s already claims to exist in our world.\n",
166                                 technology->name);
167                         AST_RWLIST_UNLOCK(&bridge_technologies);
168                         return -1;
169                 }
170         }
171
172         /* Copy module pointer so reference counting can keep the module from unloading */
173         technology->mod = module;
174
175         /* Insert our new bridge technology into the list and print out a pretty message */
176         AST_RWLIST_INSERT_TAIL(&bridge_technologies, technology, entry);
177
178         AST_RWLIST_UNLOCK(&bridge_technologies);
179
180         ast_verb(2, "Registered bridge technology %s\n", technology->name);
181
182         return 0;
183 }
184
185 int ast_bridge_technology_unregister(struct ast_bridge_technology *technology)
186 {
187         struct ast_bridge_technology *current;
188
189         AST_RWLIST_WRLOCK(&bridge_technologies);
190
191         /* Ensure the bridge technology is registered before removing it */
192         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&bridge_technologies, current, entry) {
193                 if (current == technology) {
194                         AST_RWLIST_REMOVE_CURRENT(entry);
195                         ast_verb(2, "Unregistered bridge technology %s\n", technology->name);
196                         break;
197                 }
198         }
199         AST_RWLIST_TRAVERSE_SAFE_END;
200
201         AST_RWLIST_UNLOCK(&bridge_technologies);
202
203         return current ? 0 : -1;
204 }
205
206 void ast_bridge_channel_lock_bridge(struct ast_bridge_channel *bridge_channel)
207 {
208         struct ast_bridge *bridge;
209
210         for (;;) {
211                 /* Safely get the bridge pointer */
212                 ast_bridge_channel_lock(bridge_channel);
213                 bridge = bridge_channel->bridge;
214                 ao2_ref(bridge, +1);
215                 ast_bridge_channel_unlock(bridge_channel);
216
217                 /* Lock the bridge and see if it is still the bridge we need to lock. */
218                 ast_bridge_lock(bridge);
219                 if (bridge == bridge_channel->bridge) {
220                         ao2_ref(bridge, -1);
221                         return;
222                 }
223                 ast_bridge_unlock(bridge);
224                 ao2_ref(bridge, -1);
225         }
226 }
227
228 static void bridge_channel_poke(struct ast_bridge_channel *bridge_channel)
229 {
230         if (!pthread_equal(pthread_self(), bridge_channel->thread)) {
231                 while (bridge_channel->waiting) {
232                         pthread_kill(bridge_channel->thread, SIGURG);
233                         sched_yield();
234                 }
235         }
236 }
237
238 void ast_bridge_change_state_nolock(struct ast_bridge_channel *bridge_channel, enum ast_bridge_channel_state new_state)
239 {
240 /* BUGBUG need cause code for the bridge_channel leaving the bridge. */
241         if (bridge_channel->state != AST_BRIDGE_CHANNEL_STATE_WAIT) {
242                 return;
243         }
244
245         ast_debug(1, "Setting %p(%s) state from:%d to:%d\n",
246                 bridge_channel, ast_channel_name(bridge_channel->chan), bridge_channel->state,
247                 new_state);
248
249         /* Change the state on the bridge channel */
250         bridge_channel->state = new_state;
251
252         bridge_channel_poke(bridge_channel);
253 }
254
255 void ast_bridge_change_state(struct ast_bridge_channel *bridge_channel, enum ast_bridge_channel_state new_state)
256 {
257         ast_bridge_channel_lock(bridge_channel);
258         ast_bridge_change_state_nolock(bridge_channel, new_state);
259         ast_bridge_channel_unlock(bridge_channel);
260 }
261
262 /*!
263  * \internal
264  * \brief Put an action onto the specified bridge. Don't dup the action frame.
265  * \since 12.0.0
266  *
267  * \param bridge What to queue the action on.
268  * \param action What to do.
269  *
270  * \return Nothing
271  */
272 static void bridge_queue_action_nodup(struct ast_bridge *bridge, struct ast_frame *action)
273 {
274         ast_debug(1, "Bridge %s: queueing action type:%d sub:%d\n",
275                 bridge->uniqueid, action->frametype, action->subclass.integer);
276
277         ast_bridge_lock(bridge);
278         AST_LIST_INSERT_TAIL(&bridge->action_queue, action, frame_list);
279         ast_bridge_unlock(bridge);
280         bridge_manager_service_req(bridge);
281 }
282
283 int ast_bridge_queue_action(struct ast_bridge *bridge, struct ast_frame *action)
284 {
285         struct ast_frame *dup;
286
287         dup = ast_frdup(action);
288         if (!dup) {
289                 return -1;
290         }
291         bridge_queue_action_nodup(bridge, dup);
292         return 0;
293 }
294
295 int ast_bridge_channel_queue_frame(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
296 {
297         struct ast_frame *dup;
298         char nudge = 0;
299
300         if (bridge_channel->suspended
301                 /* Also defer DTMF frames. */
302                 && fr->frametype != AST_FRAME_DTMF_BEGIN
303                 && fr->frametype != AST_FRAME_DTMF_END
304                 && !ast_is_deferrable_frame(fr)) {
305                 /* Drop non-deferable frames when suspended. */
306                 return 0;
307         }
308
309         dup = ast_frdup(fr);
310         if (!dup) {
311                 return -1;
312         }
313
314         ast_bridge_channel_lock(bridge_channel);
315         if (bridge_channel->state != AST_BRIDGE_CHANNEL_STATE_WAIT) {
316                 /* Drop frames on channels leaving the bridge. */
317                 ast_bridge_channel_unlock(bridge_channel);
318                 ast_frfree(dup);
319                 return 0;
320         }
321
322         AST_LIST_INSERT_TAIL(&bridge_channel->wr_queue, dup, frame_list);
323         if (write(bridge_channel->alert_pipe[1], &nudge, sizeof(nudge)) != sizeof(nudge)) {
324                 ast_log(LOG_ERROR, "We couldn't write alert pipe for %p(%s)... something is VERY wrong\n",
325                         bridge_channel, ast_channel_name(bridge_channel->chan));
326         }
327         ast_bridge_channel_unlock(bridge_channel);
328         return 0;
329 }
330
331 void ast_bridge_channel_queue_action_data(struct ast_bridge_channel *bridge_channel, enum ast_bridge_action_type action, const void *data, size_t datalen)
332 {
333         struct ast_frame frame = {
334                 .frametype = AST_FRAME_BRIDGE_ACTION,
335                 .subclass.integer = action,
336                 .datalen = datalen,
337                 .data.ptr = (void *) data,
338         };
339
340         ast_bridge_channel_queue_frame(bridge_channel, &frame);
341 }
342
343 void ast_bridge_channel_queue_control_data(struct ast_bridge_channel *bridge_channel, enum ast_control_frame_type control, const void *data, size_t datalen)
344 {
345         struct ast_frame frame = {
346                 .frametype = AST_FRAME_CONTROL,
347                 .subclass.integer = control,
348                 .datalen = datalen,
349                 .data.ptr = (void *) data,
350         };
351
352         ast_bridge_channel_queue_frame(bridge_channel, &frame);
353 }
354
355 void ast_bridge_channel_restore_formats(struct ast_bridge_channel *bridge_channel)
356 {
357         /* Restore original formats of the channel as they came in */
358         if (ast_format_cmp(ast_channel_readformat(bridge_channel->chan), &bridge_channel->read_format) == AST_FORMAT_CMP_NOT_EQUAL) {
359                 ast_debug(1, "Bridge is returning %p(%s) to read format %s\n",
360                         bridge_channel, ast_channel_name(bridge_channel->chan),
361                         ast_getformatname(&bridge_channel->read_format));
362                 if (ast_set_read_format(bridge_channel->chan, &bridge_channel->read_format)) {
363                         ast_debug(1, "Bridge failed to return %p(%s) to read format %s\n",
364                                 bridge_channel, ast_channel_name(bridge_channel->chan),
365                                 ast_getformatname(&bridge_channel->read_format));
366                 }
367         }
368         if (ast_format_cmp(ast_channel_writeformat(bridge_channel->chan), &bridge_channel->write_format) == AST_FORMAT_CMP_NOT_EQUAL) {
369                 ast_debug(1, "Bridge is returning %p(%s) to write format %s\n",
370                         bridge_channel, ast_channel_name(bridge_channel->chan),
371                         ast_getformatname(&bridge_channel->write_format));
372                 if (ast_set_write_format(bridge_channel->chan, &bridge_channel->write_format)) {
373                         ast_debug(1, "Bridge failed to return %p(%s) to write format %s\n",
374                                 bridge_channel, ast_channel_name(bridge_channel->chan),
375                                 ast_getformatname(&bridge_channel->write_format));
376                 }
377         }
378 }
379
380 /*!
381  * \internal
382  * \brief Helper function to find a bridge channel given a channel.
383  *
384  * \param bridge What to search
385  * \param chan What to search for.
386  *
387  * \note On entry, bridge is already locked.
388  *
389  * \retval bridge_channel if channel is in the bridge.
390  * \retval NULL if not in bridge.
391  */
392 static struct ast_bridge_channel *find_bridge_channel(struct ast_bridge *bridge, struct ast_channel *chan)
393 {
394         struct ast_bridge_channel *bridge_channel;
395
396         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
397                 if (bridge_channel->chan == chan) {
398                         break;
399                 }
400         }
401
402         return bridge_channel;
403 }
404
405 /*!
406  * \internal
407  * \brief Dissolve the bridge.
408  * \since 12.0.0
409  *
410  * \param bridge Bridge to eject all channels
411  *
412  * \details
413  * Force out all channels that are not already going out of the
414  * bridge.  Any new channels joining will leave immediately.
415  *
416  * \note On entry, bridge is already locked.
417  *
418  * \return Nothing
419  */
420 static void bridge_dissolve(struct ast_bridge *bridge)
421 {
422         struct ast_bridge_channel *bridge_channel;
423         struct ast_frame action = {
424                 .frametype = AST_FRAME_BRIDGE_ACTION,
425                 .subclass.integer = AST_BRIDGE_ACTION_DEFERRED_DISSOLVING,
426         };
427
428         if (bridge->dissolved) {
429                 return;
430         }
431         bridge->dissolved = 1;
432
433         ast_debug(1, "Bridge %s: dissolving bridge\n", bridge->uniqueid);
434
435 /* BUGBUG need a cause code on the bridge for the later ejected channels. */
436         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
437                 ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
438         }
439
440         /* Must defer dissolving bridge because it is already locked. */
441         ast_bridge_queue_action(bridge, &action);
442 }
443
444 /*!
445  * \internal
446  * \brief Check if a bridge should dissolve and do it.
447  * \since 12.0.0
448  *
449  * \param bridge_channel Channel causing the check.
450  *
451  * \note On entry, bridge_channel->bridge is already locked.
452  *
453  * \return Nothing
454  */
455 static void bridge_dissolve_check(struct ast_bridge_channel *bridge_channel)
456 {
457         struct ast_bridge *bridge = bridge_channel->bridge;
458
459         if (bridge->dissolved) {
460                 return;
461         }
462
463         if (!bridge->num_channels
464                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY)) {
465                 /* Last channel leaving the bridge turns off the lights. */
466                 bridge_dissolve(bridge);
467                 return;
468         }
469
470         switch (bridge_channel->state) {
471         case AST_BRIDGE_CHANNEL_STATE_END:
472                 /* Do we need to dissolve the bridge because this channel hung up? */
473                 if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)
474                         || (bridge_channel->features->usable
475                                 && ast_test_flag(&bridge_channel->features->feature_flags,
476                                         AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP))) {
477                         bridge_dissolve(bridge);
478                         return;
479                 }
480                 break;
481         default:
482                 break;
483         }
484 /* BUGBUG need to implement AST_BRIDGE_CHANNEL_FLAG_LONELY support here */
485 }
486
487 /*!
488  * \internal
489  * \brief Pull the bridge channel out of its current bridge.
490  * \since 12.0.0
491  *
492  * \param bridge_channel Channel to pull.
493  *
494  * \note On entry, bridge_channel->bridge is already locked.
495  *
496  * \return Nothing
497  */
498 static void bridge_channel_pull(struct ast_bridge_channel *bridge_channel)
499 {
500         struct ast_bridge *bridge = bridge_channel->bridge;
501
502         if (!bridge_channel->in_bridge) {
503                 return;
504         }
505         bridge_channel->in_bridge = 0;
506
507         ast_debug(1, "Bridge %s: pulling %p(%s)\n",
508                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
509
510 /* BUGBUG This is where incoming HOLD/UNHOLD memory should write UNHOLD into bridge. (if not local optimizing) */
511 /* BUGBUG This is where incoming DTMF begin/end memory should write DTMF end into bridge. (if not local optimizing) */
512         if (!bridge_channel->just_joined) {
513                 /* Tell the bridge technology we are leaving so they tear us down */
514                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology\n",
515                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
516                         bridge->technology->name);
517                 if (bridge->technology->leave) {
518                         bridge->technology->leave(bridge, bridge_channel);
519                 }
520         }
521
522         /* Remove channel from the bridge */
523         if (!bridge_channel->suspended) {
524                 --bridge->num_active;
525         }
526         --bridge->num_channels;
527         AST_LIST_REMOVE(&bridge->channels, bridge_channel, entry);
528         bridge->v_table->pull(bridge, bridge_channel);
529
530         ast_bridge_channel_clear_roles(bridge_channel);
531
532         bridge_dissolve_check(bridge_channel);
533
534         bridge->reconfigured = 1;
535         ast_bridge_publish_leave(bridge, bridge_channel->chan);
536 }
537
538 /*!
539  * \internal
540  * \brief Push the bridge channel into its specified bridge.
541  * \since 12.0.0
542  *
543  * \param bridge_channel Channel to push.
544  *
545  * \note On entry, bridge_channel->bridge is already locked.
546  *
547  * \retval 0 on success.
548  * \retval -1 on failure.  The channel did not get pushed.
549  */
550 static int bridge_channel_push(struct ast_bridge_channel *bridge_channel)
551 {
552         struct ast_bridge *bridge = bridge_channel->bridge;
553         struct ast_bridge_channel *swap;
554
555         ast_assert(!bridge_channel->in_bridge);
556
557         swap = find_bridge_channel(bridge, bridge_channel->swap);
558         bridge_channel->swap = NULL;
559
560         if (swap) {
561                 ast_debug(1, "Bridge %s: pushing %p(%s) by swapping with %p(%s)\n",
562                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
563                         swap, ast_channel_name(swap->chan));
564         } else {
565                 ast_debug(1, "Bridge %s: pushing %p(%s)\n",
566                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
567         }
568
569         /* Add channel to the bridge */
570         if (bridge->dissolved
571                 || bridge_channel->state != AST_BRIDGE_CHANNEL_STATE_WAIT
572                 || (swap && swap->state != AST_BRIDGE_CHANNEL_STATE_WAIT)
573                 || bridge->v_table->push(bridge, bridge_channel, swap)
574                 || ast_bridge_channel_establish_roles(bridge_channel)) {
575                 ast_debug(1, "Bridge %s: pushing %p(%s) into bridge failed\n",
576                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
577                 return -1;
578         }
579         bridge_channel->in_bridge = 1;
580         bridge_channel->just_joined = 1;
581         AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
582         ++bridge->num_channels;
583         if (!bridge_channel->suspended) {
584                 ++bridge->num_active;
585         }
586         if (swap) {
587                 ast_bridge_change_state(swap, AST_BRIDGE_CHANNEL_STATE_HANGUP);
588                 bridge_channel_pull(swap);
589         }
590
591         /* Clear any BLINDTRANSFER since the transfer has completed. */
592         pbx_builtin_setvar_helper(bridge_channel->chan, "BLINDTRANSFER", NULL);
593
594         bridge->reconfigured = 1;
595         ast_bridge_publish_enter(bridge, bridge_channel->chan);
596         return 0;
597 }
598
599 /*! \brief Internal function to handle DTMF from a channel */
600 static struct ast_frame *bridge_handle_dtmf(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
601 {
602         struct ast_bridge_features *features = bridge_channel->features;
603         struct ast_bridge_hook *hook;
604         char dtmf[2];
605
606 /* BUGBUG the feature hook matching needs to be done here.  Any matching feature hook needs to be queued onto the bridge_channel.  Also the feature hook digit timeout needs to be handled. */
607 /* BUGBUG the AMI atxfer action just sends DTMF end events to initiate DTMF atxfer and dial the extension.  Another reason the DTMF hook matching needs rework. */
608         /* See if this DTMF matches the beginnings of any feature hooks, if so we switch to the feature state to either execute the feature or collect more DTMF */
609         dtmf[0] = frame->subclass.integer;
610         dtmf[1] = '\0';
611         hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
612         if (hook) {
613                 struct ast_frame action = {
614                         .frametype = AST_FRAME_BRIDGE_ACTION,
615                         .subclass.integer = AST_BRIDGE_ACTION_FEATURE,
616                 };
617
618                 ast_frfree(frame);
619                 frame = NULL;
620                 ast_bridge_channel_queue_frame(bridge_channel, &action);
621                 ao2_ref(hook, -1);
622         }
623
624         return frame;
625 }
626
627 /*!
628  * \internal
629  * \brief Handle bridge hangup event.
630  * \since 12.0.0
631  *
632  * \param bridge_channel Which channel is hanging up.
633  *
634  * \return Nothing
635  */
636 static void bridge_handle_hangup(struct ast_bridge_channel *bridge_channel)
637 {
638         struct ast_bridge_features *features = bridge_channel->features;
639         struct ast_bridge_hook *hook;
640         struct ao2_iterator iter;
641
642         /* Run any hangup hooks. */
643         iter = ao2_iterator_init(features->hangup_hooks, 0);
644         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
645                 int failed;
646
647                 failed = hook->callback(bridge_channel->bridge, bridge_channel, hook->hook_pvt);
648                 if (failed) {
649                         ast_debug(1, "Hangup hook %p is being removed from %p(%s)\n",
650                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
651                         ao2_unlink(features->hangup_hooks, hook);
652                 }
653         }
654         ao2_iterator_destroy(&iter);
655
656         /* Default hangup action. */
657         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_END);
658 }
659
660 static int bridge_channel_interval_ready(struct ast_bridge_channel *bridge_channel)
661 {
662         struct ast_bridge_features *features = bridge_channel->features;
663         struct ast_bridge_hook *hook;
664         int ready;
665
666         ast_heap_wrlock(features->interval_hooks);
667         hook = ast_heap_peek(features->interval_hooks, 1);
668         ready = hook && ast_tvdiff_ms(hook->parms.timer.trip_time, ast_tvnow()) <= 0;
669         ast_heap_unlock(features->interval_hooks);
670
671         return ready;
672 }
673
674 void ast_bridge_notify_talking(struct ast_bridge_channel *bridge_channel, int started_talking)
675 {
676         struct ast_frame action = {
677                 .frametype = AST_FRAME_BRIDGE_ACTION,
678                 .subclass.integer = started_talking
679                         ? AST_BRIDGE_ACTION_TALKING_START : AST_BRIDGE_ACTION_TALKING_STOP,
680         };
681
682         ast_bridge_channel_queue_frame(bridge_channel, &action);
683 }
684
685 static void bridge_channel_write_frame(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
686 {
687         ast_bridge_channel_lock_bridge(bridge_channel);
688 /*
689  * BUGBUG need to implement a deferred write queue for when there is no peer channel in the bridge (yet or it was kicked).
690  *
691  * The tech decides if a frame needs to be pushed back for deferral.
692  * simple_bridge/native_bridge are likely the only techs that will do this.
693  */
694         bridge_channel->bridge->technology->write(bridge_channel->bridge, bridge_channel, frame);
695         ast_bridge_unlock(bridge_channel->bridge);
696 }
697
698 void ast_bridge_channel_write_action_data(struct ast_bridge_channel *bridge_channel, enum ast_bridge_action_type action, const void *data, size_t datalen)
699 {
700         struct ast_frame frame = {
701                 .frametype = AST_FRAME_BRIDGE_ACTION,
702                 .subclass.integer = action,
703                 .datalen = datalen,
704                 .data.ptr = (void *) data,
705         };
706
707         bridge_channel_write_frame(bridge_channel, &frame);
708 }
709
710 void ast_bridge_channel_write_control_data(struct ast_bridge_channel *bridge_channel, enum ast_control_frame_type control, const void *data, size_t datalen)
711 {
712         struct ast_frame frame = {
713                 .frametype = AST_FRAME_CONTROL,
714                 .subclass.integer = control,
715                 .datalen = datalen,
716                 .data.ptr = (void *) data,
717         };
718
719         bridge_channel_write_frame(bridge_channel, &frame);
720 }
721
722 void ast_bridge_channel_write_hold(struct ast_bridge_channel *bridge_channel, const char *moh_class)
723 {
724         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
725         size_t datalen;
726
727         if (!ast_strlen_zero(moh_class)) {
728                 datalen = strlen(moh_class) + 1;
729
730                 blob = ast_json_pack("{s: s}",
731                         "musicclass", moh_class);
732         } else {
733                 moh_class = NULL;
734                 datalen = 0;
735         }
736
737         ast_channel_publish_blob(bridge_channel->chan, ast_channel_hold_type(), blob);
738         ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_HOLD, moh_class,
739                 datalen);
740 }
741
742 void ast_bridge_channel_write_unhold(struct ast_bridge_channel *bridge_channel)
743 {
744         ast_channel_publish_blob(bridge_channel->chan, ast_channel_unhold_type(), NULL);
745         ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_UNHOLD, NULL, 0);
746 }
747
748 static int run_app_helper(struct ast_channel *chan, const char *app_name, const char *app_args)
749 {
750         int res = 0;
751
752         if (!strcasecmp("Gosub", app_name)) {
753                 ast_app_exec_sub(NULL, chan, app_args, 0);
754         } else if (!strcasecmp("Macro", app_name)) {
755                 ast_app_exec_macro(NULL, chan, app_args);
756         } else {
757                 struct ast_app *app;
758
759                 app = pbx_findapp(app_name);
760                 if (!app) {
761                         ast_log(LOG_WARNING, "Could not find application (%s)\n", app_name);
762                 } else {
763                         res = pbx_exec(chan, app, app_args);
764                 }
765         }
766         return res;
767 }
768
769 void ast_bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
770 {
771         if (moh_class) {
772                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
773         }
774         if (run_app_helper(bridge_channel->chan, app_name, S_OR(app_args, ""))) {
775                 /* Break the bridge if the app returns non-zero. */
776                 bridge_handle_hangup(bridge_channel);
777         }
778         if (moh_class) {
779                 ast_bridge_channel_write_unhold(bridge_channel);
780         }
781 }
782
783 struct bridge_run_app {
784         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
785         int moh_offset;
786         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
787         int app_args_offset;
788         /*! Application name to run. */
789         char app_name[0];
790 };
791
792 /*!
793  * \internal
794  * \brief Handle the run application bridge action.
795  * \since 12.0.0
796  *
797  * \param bridge_channel Which channel to run the application on.
798  * \param data Action frame data to run the application.
799  *
800  * \return Nothing
801  */
802 static void bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, struct bridge_run_app *data)
803 {
804         ast_bridge_channel_run_app(bridge_channel, data->app_name,
805                 data->app_args_offset ? &data->app_name[data->app_args_offset] : NULL,
806                 data->moh_offset ? &data->app_name[data->moh_offset] : NULL);
807 }
808
809 static void payload_helper_app(ast_bridge_channel_post_action_data post_it,
810         struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
811 {
812         struct bridge_run_app *app_data;
813         size_t len_name = strlen(app_name) + 1;
814         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
815         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
816         size_t len_data = sizeof(*app_data) + len_name + len_args + len_moh;
817
818         /* Fill in application run frame data. */
819         app_data = alloca(len_data);
820         app_data->app_args_offset = len_args ? len_name : 0;
821         app_data->moh_offset = len_moh ? len_name + len_args : 0;
822         strcpy(app_data->app_name, app_name);/* Safe */
823         if (len_args) {
824                 strcpy(&app_data->app_name[app_data->app_args_offset], app_args);/* Safe */
825         }
826         if (moh_class) {
827                 strcpy(&app_data->app_name[app_data->moh_offset], moh_class);/* Safe */
828         }
829
830         post_it(bridge_channel, AST_BRIDGE_ACTION_RUN_APP, app_data, len_data);
831 }
832
833 void ast_bridge_channel_write_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
834 {
835         payload_helper_app(ast_bridge_channel_write_action_data,
836                 bridge_channel, app_name, app_args, moh_class);
837 }
838
839 void ast_bridge_channel_queue_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
840 {
841         payload_helper_app(ast_bridge_channel_queue_action_data,
842                 bridge_channel, app_name, app_args, moh_class);
843 }
844
845 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)
846 {
847         if (moh_class) {
848                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
849         }
850         if (custom_play) {
851                 custom_play(bridge_channel, playfile);
852         } else {
853                 ast_stream_and_wait(bridge_channel->chan, playfile, AST_DIGIT_NONE);
854         }
855         if (moh_class) {
856                 ast_bridge_channel_write_unhold(bridge_channel);
857         }
858
859         /*
860          * It may be necessary to resume music on hold after we finish
861          * playing the announcment.
862          *
863          * XXX We have no idea what MOH class was in use before playing
864          * the file.
865          */
866         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_MOH)) {
867                 ast_moh_start(bridge_channel->chan, NULL, NULL);
868         }
869 }
870
871 struct bridge_playfile {
872         /*! Call this function to play the playfile. (NULL if normal sound file to play) */
873         ast_bridge_custom_play_fn custom_play;
874         /*! Offset into playfile[] where the MOH class name starts.  (zero if no MOH)*/
875         int moh_offset;
876         /*! Filename to play. */
877         char playfile[0];
878 };
879
880 /*!
881  * \internal
882  * \brief Handle the playfile bridge action.
883  * \since 12.0.0
884  *
885  * \param bridge_channel Which channel to play a file on.
886  * \param payload Action frame payload to play a file.
887  *
888  * \return Nothing
889  */
890 static void bridge_channel_playfile(struct ast_bridge_channel *bridge_channel, struct bridge_playfile *payload)
891 {
892         ast_bridge_channel_playfile(bridge_channel, payload->custom_play, payload->playfile,
893                 payload->moh_offset ? &payload->playfile[payload->moh_offset] : NULL);
894 }
895
896 static void payload_helper_playfile(ast_bridge_channel_post_action_data post_it,
897         struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
898 {
899         struct bridge_playfile *payload;
900         size_t len_name = strlen(playfile) + 1;
901         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
902         size_t len_payload = sizeof(*payload) + len_name + len_moh;
903
904         /* Fill in play file frame data. */
905         payload = alloca(len_payload);
906         payload->custom_play = custom_play;
907         payload->moh_offset = len_moh ? len_name : 0;
908         strcpy(payload->playfile, playfile);/* Safe */
909         if (moh_class) {
910                 strcpy(&payload->playfile[payload->moh_offset], moh_class);/* Safe */
911         }
912
913         post_it(bridge_channel, AST_BRIDGE_ACTION_PLAY_FILE, payload, len_payload);
914 }
915
916 void 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)
917 {
918         payload_helper_playfile(ast_bridge_channel_write_action_data,
919                 bridge_channel, custom_play, playfile, moh_class);
920 }
921
922 void 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)
923 {
924         payload_helper_playfile(ast_bridge_channel_queue_action_data,
925                 bridge_channel, custom_play, playfile, moh_class);
926 }
927
928 struct bridge_custom_callback {
929         /*! Call this function on the bridge channel thread. */
930         ast_bridge_custom_callback_fn callback;
931         /*! Size of the payload if it exists.  A number otherwise. */
932         size_t payload_size;
933         /*! Nonzero if the payload exists. */
934         char payload_exists;
935         /*! Payload to give to callback. */
936         char payload[0];
937 };
938
939 /*!
940  * \internal
941  * \brief Handle the do custom callback bridge action.
942  * \since 12.0.0
943  *
944  * \param bridge_channel Which channel to run the application on.
945  * \param data Action frame data to run the application.
946  *
947  * \return Nothing
948  */
949 static void bridge_channel_do_callback(struct ast_bridge_channel *bridge_channel, struct bridge_custom_callback *data)
950 {
951         data->callback(bridge_channel, data->payload_exists ? data->payload : NULL, data->payload_size);
952 }
953
954 static void payload_helper_cb(ast_bridge_channel_post_action_data post_it,
955         struct ast_bridge_channel *bridge_channel, ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
956 {
957         struct bridge_custom_callback *cb_data;
958         size_t len_data = sizeof(*cb_data) + (payload ? payload_size : 0);
959
960         /* Sanity check. */
961         if (!callback) {
962                 ast_assert(0);
963                 return;
964         }
965
966         /* Fill in custom callback frame data. */
967         cb_data = alloca(len_data);
968         cb_data->callback = callback;
969         cb_data->payload_size = payload_size;
970         cb_data->payload_exists = payload && payload_size;
971         if (cb_data->payload_exists) {
972                 memcpy(cb_data->payload, payload, payload_size);/* Safe */
973         }
974
975         post_it(bridge_channel, AST_BRIDGE_ACTION_CALLBACK, cb_data, len_data);
976 }
977
978 void ast_bridge_channel_write_callback(struct ast_bridge_channel *bridge_channel, ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
979 {
980         payload_helper_cb(ast_bridge_channel_write_action_data,
981                 bridge_channel, callback, payload, payload_size);
982 }
983
984 void ast_bridge_channel_queue_callback(struct ast_bridge_channel *bridge_channel, ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
985 {
986         payload_helper_cb(ast_bridge_channel_queue_action_data,
987                 bridge_channel, callback, payload, payload_size);
988 }
989
990 struct bridge_park {
991         int parker_uuid_offset;
992         int app_data_offset;
993         /* buffer used for holding those strings */
994         char parkee_uuid[0];
995 };
996
997 static void bridge_channel_park(struct ast_bridge_channel *bridge_channel, struct bridge_park *payload)
998 {
999         ast_bridge_channel_park(bridge_channel, payload->parkee_uuid,
1000                 &payload->parkee_uuid[payload->parker_uuid_offset],
1001                 payload->app_data_offset ? &payload->parkee_uuid[payload->app_data_offset] : NULL);
1002 }
1003
1004 static void payload_helper_park(ast_bridge_channel_post_action_data post_it,
1005         struct ast_bridge_channel *bridge_channel,
1006         const char *parkee_uuid,
1007         const char *parker_uuid,
1008         const char *app_data)
1009 {
1010         struct bridge_park *payload;
1011         size_t len_parkee_uuid = strlen(parkee_uuid) + 1;
1012         size_t len_parker_uuid = strlen(parker_uuid) + 1;
1013         size_t len_app_data = !app_data ? 0 : strlen(app_data) + 1;
1014         size_t len_payload = sizeof(*payload) + len_parker_uuid + len_parkee_uuid + len_app_data;
1015
1016         payload = alloca(len_payload);
1017         payload->app_data_offset = len_app_data ? len_parkee_uuid + len_parker_uuid : 0;
1018         payload->parker_uuid_offset = len_parkee_uuid;
1019         strcpy(payload->parkee_uuid, parkee_uuid);
1020         strcpy(&payload->parkee_uuid[payload->parker_uuid_offset], parker_uuid);
1021         if (app_data) {
1022                 strcpy(&payload->parkee_uuid[payload->app_data_offset], app_data);
1023         }
1024
1025         post_it(bridge_channel, AST_BRIDGE_ACTION_PARK, payload, len_payload);
1026 }
1027
1028 void ast_bridge_channel_write_park(struct ast_bridge_channel *bridge_channel, const char *parkee_uuid, const char *parker_uuid, const char *app_data)
1029 {
1030         payload_helper_park(ast_bridge_channel_write_action_data,
1031                 bridge_channel, parkee_uuid, parker_uuid, app_data);
1032 }
1033
1034 /*!
1035  * \internal
1036  * \brief Feed notification that a frame is waiting on a channel into the bridging core
1037  *
1038  * \param bridge_channel Bridge channel the notification was received on
1039  */
1040 static void bridge_handle_trip(struct ast_bridge_channel *bridge_channel)
1041 {
1042         struct ast_frame *frame;
1043
1044         if (bridge_channel->features->mute) {
1045                 frame = ast_read_noaudio(bridge_channel->chan);
1046         } else {
1047                 frame = ast_read(bridge_channel->chan);
1048         }
1049
1050         if (!frame) {
1051                 bridge_handle_hangup(bridge_channel);
1052                 return;
1053         }
1054         switch (frame->frametype) {
1055         case AST_FRAME_NULL:
1056                 /* Just discard it. */
1057                 ast_frfree(frame);
1058                 return;
1059         case AST_FRAME_CONTROL:
1060                 switch (frame->subclass.integer) {
1061                 case AST_CONTROL_HANGUP:
1062                         bridge_handle_hangup(bridge_channel);
1063                         ast_frfree(frame);
1064                         return;
1065 /* BUGBUG This is where incoming HOLD/UNHOLD memory should register.  Write UNHOLD into bridge when this channel is pulled. */
1066                 default:
1067                         break;
1068                 }
1069                 break;
1070         case AST_FRAME_DTMF_BEGIN:
1071                 frame = bridge_handle_dtmf(bridge_channel, frame);
1072                 if (!frame) {
1073                         return;
1074                 }
1075                 /* Fall through */
1076         case AST_FRAME_DTMF_END:
1077                 if (!bridge_channel->features->dtmf_passthrough) {
1078                         ast_frfree(frame);
1079                         return;
1080                 }
1081 /* BUGBUG This is where incoming DTMF begin/end memory should register.  Write DTMF end into bridge when this channel is pulled. */
1082                 break;
1083         default:
1084                 break;
1085         }
1086
1087 /* BUGBUG bridge join or impart needs to do CONNECTED_LINE updates if the channels are being swapped and it is a 1-1 bridge. */
1088
1089         /* Simply write the frame out to the bridge technology. */
1090 /* BUGBUG The tech is where AST_CONTROL_ANSWER hook should go. (early bridge) */
1091 /* BUGBUG The tech is where incoming BUSY/CONGESTION hangup should happen? (early bridge) */
1092         bridge_channel_write_frame(bridge_channel, frame);
1093         ast_frfree(frame);
1094 }
1095
1096 /*!
1097  * \internal
1098  * \brief Complete joining new channels to the bridge.
1099  * \since 12.0.0
1100  *
1101  * \param bridge Check for new channels on this bridge.
1102  *
1103  * \note On entry, bridge is already locked.
1104  *
1105  * \return Nothing
1106  */
1107 static void bridge_complete_join(struct ast_bridge *bridge)
1108 {
1109         struct ast_bridge_channel *bridge_channel;
1110
1111         if (bridge->dissolved) {
1112                 /*
1113                  * No sense in completing the join on channels for a dissolved
1114                  * bridge.  They are just going to be removed soon anyway.
1115                  * However, we do have reason to abort here because the bridge
1116                  * technology may not be able to handle the number of channels
1117                  * still in the bridge.
1118                  */
1119                 return;
1120         }
1121
1122         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1123                 if (!bridge_channel->just_joined) {
1124                         continue;
1125                 }
1126
1127                 /* Make the channel compatible with the bridge */
1128                 bridge_make_compatible(bridge, bridge_channel);
1129
1130                 /* Tell the bridge technology we are joining so they set us up */
1131                 ast_debug(1, "Bridge %s: %p(%s) is joining %s technology\n",
1132                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1133                         bridge->technology->name);
1134                 if (bridge->technology->join
1135                         && bridge->technology->join(bridge, bridge_channel)) {
1136                         ast_debug(1, "Bridge %s: %p(%s) failed to join %s technology\n",
1137                                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1138                                 bridge->technology->name);
1139                 }
1140
1141                 bridge_channel->just_joined = 0;
1142         }
1143 }
1144
1145 /*! \brief Helper function used to find the "best" bridge technology given specified capabilities */
1146 static struct ast_bridge_technology *find_best_technology(uint32_t capabilities, struct ast_bridge *bridge)
1147 {
1148         struct ast_bridge_technology *current;
1149         struct ast_bridge_technology *best = NULL;
1150
1151         AST_RWLIST_RDLOCK(&bridge_technologies);
1152         AST_RWLIST_TRAVERSE(&bridge_technologies, current, entry) {
1153                 if (current->suspended) {
1154                         ast_debug(1, "Bridge technology %s is suspended. Skipping.\n",
1155                                 current->name);
1156                         continue;
1157                 }
1158                 if (!(current->capabilities & capabilities)) {
1159                         ast_debug(1, "Bridge technology %s does not have any capabilities we want.\n",
1160                                 current->name);
1161                         continue;
1162                 }
1163                 if (best && current->preference <= best->preference) {
1164                         ast_debug(1, "Bridge technology %s has less preference than %s (%d <= %d). Skipping.\n",
1165                                 current->name, best->name, current->preference, best->preference);
1166                         continue;
1167                 }
1168                 if (current->compatible && !current->compatible(bridge)) {
1169                         ast_debug(1, "Bridge technology %s is not compatible with properties of existing bridge.\n",
1170                                 current->name);
1171                         continue;
1172                 }
1173                 best = current;
1174         }
1175
1176         if (best) {
1177                 /* Increment it's module reference count if present so it does not get unloaded while in use */
1178                 ast_module_ref(best->mod);
1179                 ast_debug(1, "Chose bridge technology %s\n", best->name);
1180         }
1181
1182         AST_RWLIST_UNLOCK(&bridge_technologies);
1183
1184         return best;
1185 }
1186
1187 struct tech_deferred_destroy {
1188         struct ast_bridge_technology *tech;
1189         void *tech_pvt;
1190 };
1191
1192 /*!
1193  * \internal
1194  * \brief Deferred destruction of bridge tech private structure.
1195  * \since 12.0.0
1196  *
1197  * \param bridge What to execute the action on.
1198  * \param action Deferred bridge tech destruction.
1199  *
1200  * \note On entry, bridge must not be locked.
1201  *
1202  * \return Nothing
1203  */
1204 static void bridge_tech_deferred_destroy(struct ast_bridge *bridge, struct ast_frame *action)
1205 {
1206         struct tech_deferred_destroy *deferred = action->data.ptr;
1207         struct ast_bridge dummy_bridge = {
1208                 .technology = deferred->tech,
1209                 .tech_pvt = deferred->tech_pvt,
1210                 };
1211
1212         ast_copy_string(dummy_bridge.uniqueid, bridge->uniqueid, sizeof(dummy_bridge.uniqueid));
1213         ast_debug(1, "Bridge %s: calling %s technology destructor (deferred, dummy)\n",
1214                 dummy_bridge.uniqueid, dummy_bridge.technology->name);
1215         dummy_bridge.technology->destroy(&dummy_bridge);
1216         ast_module_unref(dummy_bridge.technology->mod);
1217 }
1218
1219 /*!
1220  * \internal
1221  * \brief Handle bridge action frame.
1222  * \since 12.0.0
1223  *
1224  * \param bridge What to execute the action on.
1225  * \param action What to do.
1226  *
1227  * \note On entry, bridge is already locked.
1228  * \note Can be called by the bridge destructor.
1229  *
1230  * \return Nothing
1231  */
1232 static void bridge_action_bridge(struct ast_bridge *bridge, struct ast_frame *action)
1233 {
1234 #if 0   /* In case we need to know when the destructor is calling us. */
1235         int in_destructor = !ao2_ref(bridge, 0);
1236 #endif
1237
1238         switch (action->subclass.integer) {
1239         case AST_BRIDGE_ACTION_DEFERRED_TECH_DESTROY:
1240                 ast_bridge_unlock(bridge);
1241                 bridge_tech_deferred_destroy(bridge, action);
1242                 ast_bridge_lock(bridge);
1243                 break;
1244         case AST_BRIDGE_ACTION_DEFERRED_DISSOLVING:
1245                 ast_bridge_unlock(bridge);
1246                 bridge->v_table->dissolving(bridge);
1247                 ast_bridge_lock(bridge);
1248                 break;
1249         default:
1250                 /* Unexpected deferred action type.  Should never happen. */
1251                 ast_assert(0);
1252                 break;
1253         }
1254 }
1255
1256 /*!
1257  * \internal
1258  * \brief Do any pending bridge actions.
1259  * \since 12.0.0
1260  *
1261  * \param bridge What to do actions on.
1262  *
1263  * \note On entry, bridge is already locked.
1264  * \note Can be called by the bridge destructor.
1265  *
1266  * \return Nothing
1267  */
1268 static void bridge_handle_actions(struct ast_bridge *bridge)
1269 {
1270         struct ast_frame *action;
1271
1272         while ((action = AST_LIST_REMOVE_HEAD(&bridge->action_queue, frame_list))) {
1273                 switch (action->frametype) {
1274                 case AST_FRAME_BRIDGE_ACTION:
1275                         bridge_action_bridge(bridge, action);
1276                         break;
1277                 default:
1278                         /* Unexpected deferred frame type.  Should never happen. */
1279                         ast_assert(0);
1280                         break;
1281                 }
1282                 ast_frfree(action);
1283         }
1284 }
1285
1286 static void destroy_bridge(void *obj)
1287 {
1288         struct ast_bridge *bridge = obj;
1289         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
1290
1291         ast_debug(1, "Bridge %s: actually destroying %s bridge, nobody wants it anymore\n",
1292                 bridge->uniqueid, bridge->v_table->name);
1293
1294         msg = stasis_cache_clear_create(ast_bridge_snapshot_type(), bridge->uniqueid);
1295         if (msg) {
1296                 stasis_publish(ast_bridge_topic(bridge), msg);
1297         }
1298
1299         /* Do any pending actions in the context of destruction. */
1300         ast_bridge_lock(bridge);
1301         bridge_handle_actions(bridge);
1302         ast_bridge_unlock(bridge);
1303
1304         /* There should not be any channels left in the bridge. */
1305         ast_assert(AST_LIST_EMPTY(&bridge->channels));
1306
1307         ast_debug(1, "Bridge %s: calling %s bridge destructor\n",
1308                 bridge->uniqueid, bridge->v_table->name);
1309         bridge->v_table->destroy(bridge);
1310
1311         /* Pass off the bridge to the technology to destroy if needed */
1312         if (bridge->technology) {
1313                 ast_debug(1, "Bridge %s: calling %s technology destructor\n",
1314                         bridge->uniqueid, bridge->technology->name);
1315                 if (bridge->technology->destroy) {
1316                         bridge->technology->destroy(bridge);
1317                 }
1318                 ast_module_unref(bridge->technology->mod);
1319                 bridge->technology = NULL;
1320         }
1321
1322         if (bridge->callid) {
1323                 bridge->callid = ast_callid_unref(bridge->callid);
1324         }
1325
1326         cleanup_video_mode(bridge);
1327 }
1328
1329 struct ast_bridge *ast_bridge_register(struct ast_bridge *bridge)
1330 {
1331         if (bridge) {
1332                 ast_bridge_publish_state(bridge);
1333                 if (!ao2_link(bridges, bridge)) {
1334                         ast_bridge_destroy(bridge);
1335                         bridge = NULL;
1336                 }
1337         }
1338         return bridge;
1339 }
1340
1341 struct ast_bridge *ast_bridge_alloc(size_t size, const struct ast_bridge_methods *v_table)
1342 {
1343         struct ast_bridge *bridge;
1344
1345         /* Check v_table that all methods are present. */
1346         if (!v_table
1347                 || !v_table->name
1348                 || !v_table->destroy
1349                 || !v_table->dissolving
1350                 || !v_table->push
1351                 || !v_table->pull
1352                 || !v_table->notify_masquerade
1353                 || !v_table->get_merge_priority) {
1354                 ast_log(LOG_ERROR, "Virtual method table for bridge class %s not complete.\n",
1355                         v_table && v_table->name ? v_table->name : "<unknown>");
1356                 ast_assert(0);
1357                 return NULL;
1358         }
1359
1360         bridge = ao2_alloc(size, destroy_bridge);
1361         if (bridge) {
1362                 bridge->v_table = v_table;
1363         }
1364         return bridge;
1365 }
1366
1367 struct ast_bridge *ast_bridge_base_init(struct ast_bridge *self, uint32_t capabilities, unsigned int flags)
1368 {
1369         if (!self) {
1370                 return NULL;
1371         }
1372
1373         ast_uuid_generate_str(self->uniqueid, sizeof(self->uniqueid));
1374         ast_set_flag(&self->feature_flags, flags);
1375         self->allowed_capabilities = capabilities;
1376
1377         /* Use our helper function to find the "best" bridge technology. */
1378         self->technology = find_best_technology(capabilities, self);
1379         if (!self->technology) {
1380                 ast_debug(1, "Bridge %s: Could not create.  No technology available to support it.\n",
1381                         self->uniqueid);
1382                 ao2_ref(self, -1);
1383                 return NULL;
1384         }
1385
1386         /* Pass off the bridge to the technology to manipulate if needed */
1387         ast_debug(1, "Bridge %s: calling %s technology constructor\n",
1388                 self->uniqueid, self->technology->name);
1389         if (self->technology->create && self->technology->create(self)) {
1390                 ast_debug(1, "Bridge %s: failed to setup %s technology\n",
1391                         self->uniqueid, self->technology->name);
1392                 ao2_ref(self, -1);
1393                 return NULL;
1394         }
1395
1396         if (!ast_bridge_topic(self)) {
1397                 ao2_ref(self, -1);
1398                 return NULL;
1399         }
1400
1401         return self;
1402 }
1403
1404 /*!
1405  * \internal
1406  * \brief ast_bridge base class destructor.
1407  * \since 12.0.0
1408  *
1409  * \param self Bridge to operate upon.
1410  *
1411  * \note Stub because of nothing to do.
1412  *
1413  * \return Nothing
1414  */
1415 static void bridge_base_destroy(struct ast_bridge *self)
1416 {
1417 }
1418
1419 /*!
1420  * \internal
1421  * \brief The bridge is being dissolved.
1422  * \since 12.0.0
1423  *
1424  * \param self Bridge to operate upon.
1425  *
1426  * \return Nothing
1427  */
1428 static void bridge_base_dissolving(struct ast_bridge *self)
1429 {
1430         ao2_unlink(bridges, self);
1431 }
1432
1433 /*!
1434  * \internal
1435  * \brief ast_bridge base push method.
1436  * \since 12.0.0
1437  *
1438  * \param self Bridge to operate upon.
1439  * \param bridge_channel Bridge channel to push.
1440  * \param swap Bridge channel to swap places with if not NULL.
1441  *
1442  * \note On entry, self is already locked.
1443  * \note Stub because of nothing to do.
1444  *
1445  * \retval 0 on success
1446  * \retval -1 on failure
1447  */
1448 static int bridge_base_push(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
1449 {
1450         return 0;
1451 }
1452
1453 /*!
1454  * \internal
1455  * \brief ast_bridge base pull method.
1456  * \since 12.0.0
1457  *
1458  * \param self Bridge to operate upon.
1459  * \param bridge_channel Bridge channel to pull.
1460  *
1461  * \note On entry, self is already locked.
1462  *
1463  * \return Nothing
1464  */
1465 static void bridge_base_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
1466 {
1467         bridge_features_remove(bridge_channel->features, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
1468 }
1469
1470 /*!
1471  * \internal
1472  * \brief ast_bridge base notify_masquerade method.
1473  * \since 12.0.0
1474  *
1475  * \param self Bridge to operate upon.
1476  * \param bridge_channel Bridge channel that was masqueraded.
1477  *
1478  * \note On entry, self is already locked.
1479  *
1480  * \return Nothing
1481  */
1482 static void bridge_base_notify_masquerade(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
1483 {
1484         self->reconfigured = 1;
1485 }
1486
1487 /*!
1488  * \internal
1489  * \brief Get the merge priority of this bridge.
1490  * \since 12.0.0
1491  *
1492  * \param self Bridge to operate upon.
1493  *
1494  * \note On entry, self is already locked.
1495  *
1496  * \return Merge priority
1497  */
1498 static int bridge_base_get_merge_priority(struct ast_bridge *self)
1499 {
1500         return 0;
1501 }
1502
1503 struct ast_bridge_methods ast_bridge_base_v_table = {
1504         .name = "base",
1505         .destroy = bridge_base_destroy,
1506         .dissolving = bridge_base_dissolving,
1507         .push = bridge_base_push,
1508         .pull = bridge_base_pull,
1509         .notify_masquerade = bridge_base_notify_masquerade,
1510         .get_merge_priority = bridge_base_get_merge_priority,
1511 };
1512
1513 struct ast_bridge *ast_bridge_base_new(uint32_t capabilities, unsigned int flags)
1514 {
1515         void *bridge;
1516
1517         bridge = ast_bridge_alloc(sizeof(struct ast_bridge), &ast_bridge_base_v_table);
1518         bridge = ast_bridge_base_init(bridge, capabilities, flags);
1519         bridge = ast_bridge_register(bridge);
1520         return bridge;
1521 }
1522
1523 int ast_bridge_destroy(struct ast_bridge *bridge)
1524 {
1525         ast_debug(1, "Bridge %s: telling all channels to leave the party\n", bridge->uniqueid);
1526         ast_bridge_lock(bridge);
1527         bridge_dissolve(bridge);
1528         ast_bridge_unlock(bridge);
1529
1530         ao2_ref(bridge, -1);
1531
1532         return 0;
1533 }
1534
1535 static int bridge_make_compatible(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
1536 {
1537         struct ast_format read_format;
1538         struct ast_format write_format;
1539         struct ast_format best_format;
1540         char codec_buf[512];
1541
1542         ast_format_copy(&read_format, ast_channel_readformat(bridge_channel->chan));
1543         ast_format_copy(&write_format, ast_channel_writeformat(bridge_channel->chan));
1544
1545         /* Are the formats currently in use something this bridge can handle? */
1546         if (!ast_format_cap_iscompatible(bridge->technology->format_capabilities, ast_channel_readformat(bridge_channel->chan))) {
1547                 ast_best_codec(bridge->technology->format_capabilities, &best_format);
1548
1549                 /* Read format is a no go... */
1550                 ast_debug(1, "Bridge technology %s wants to read any of formats %s but channel has %s\n",
1551                         bridge->technology->name,
1552                         ast_getformatname_multiple(codec_buf, sizeof(codec_buf), bridge->technology->format_capabilities),
1553                         ast_getformatname(&read_format));
1554
1555                 /* Switch read format to the best one chosen */
1556                 if (ast_set_read_format(bridge_channel->chan, &best_format)) {
1557                         ast_log(LOG_WARNING, "Failed to set channel %s to read format %s\n",
1558                                 ast_channel_name(bridge_channel->chan), ast_getformatname(&best_format));
1559                         return -1;
1560                 }
1561                 ast_debug(1, "Bridge %s put channel %s into read format %s\n",
1562                         bridge->uniqueid, ast_channel_name(bridge_channel->chan),
1563                         ast_getformatname(&best_format));
1564         } else {
1565                 ast_debug(1, "Bridge %s is happy that channel %s already has read format %s\n",
1566                         bridge->uniqueid, ast_channel_name(bridge_channel->chan),
1567                         ast_getformatname(&read_format));
1568         }
1569
1570         if (!ast_format_cap_iscompatible(bridge->technology->format_capabilities, &write_format)) {
1571                 ast_best_codec(bridge->technology->format_capabilities, &best_format);
1572
1573                 /* Write format is a no go... */
1574                 ast_debug(1, "Bridge technology %s wants to write any of formats %s but channel has %s\n",
1575                         bridge->technology->name,
1576                         ast_getformatname_multiple(codec_buf, sizeof(codec_buf), bridge->technology->format_capabilities),
1577                         ast_getformatname(&write_format));
1578
1579                 /* Switch write format to the best one chosen */
1580                 if (ast_set_write_format(bridge_channel->chan, &best_format)) {
1581                         ast_log(LOG_WARNING, "Failed to set channel %s to write format %s\n",
1582                                 ast_channel_name(bridge_channel->chan), ast_getformatname(&best_format));
1583                         return -1;
1584                 }
1585                 ast_debug(1, "Bridge %s put channel %s into write format %s\n",
1586                         bridge->uniqueid, ast_channel_name(bridge_channel->chan),
1587                         ast_getformatname(&best_format));
1588         } else {
1589                 ast_debug(1, "Bridge %s is happy that channel %s already has write format %s\n",
1590                         bridge->uniqueid, ast_channel_name(bridge_channel->chan),
1591                         ast_getformatname(&write_format));
1592         }
1593
1594         return 0;
1595 }
1596
1597 /*!
1598  * \internal
1599  * \brief Perform the smart bridge operation.
1600  * \since 12.0.0
1601  *
1602  * \param bridge Work on this bridge.
1603  *
1604  * \details
1605  * Basically see if a new bridge technology should be used instead
1606  * of the current one.
1607  *
1608  * \note On entry, bridge is already locked.
1609  *
1610  * \retval 0 on success.
1611  * \retval -1 on error.
1612  */
1613 static int smart_bridge_operation(struct ast_bridge *bridge)
1614 {
1615         uint32_t new_capabilities;
1616         struct ast_bridge_technology *new_technology;
1617         struct ast_bridge_technology *old_technology = bridge->technology;
1618         struct ast_bridge_channel *bridge_channel;
1619         struct ast_frame *deferred_action;
1620         struct ast_bridge dummy_bridge = {
1621                 .technology = bridge->technology,
1622                 .tech_pvt = bridge->tech_pvt,
1623         };
1624
1625         if (bridge->dissolved) {
1626                 ast_debug(1, "Bridge %s is dissolved, not performing smart bridge operation.\n",
1627                         bridge->uniqueid);
1628                 return 0;
1629         }
1630
1631         /* Determine new bridge technology capabilities needed. */
1632         if (2 < bridge->num_channels) {
1633                 new_capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX;
1634                 new_capabilities &= bridge->allowed_capabilities;
1635         } else {
1636                 new_capabilities = AST_BRIDGE_CAPABILITY_NATIVE | AST_BRIDGE_CAPABILITY_1TO1MIX;
1637                 new_capabilities &= bridge->allowed_capabilities;
1638                 if (!new_capabilities
1639                         && (bridge->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
1640                         /* Allow switching between different multimix bridge technologies. */
1641                         new_capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX;
1642                 }
1643         }
1644
1645         /* Find a bridge technology to satisfy the new capabilities. */
1646         new_technology = find_best_technology(new_capabilities, bridge);
1647         if (!new_technology) {
1648                 int is_compatible = 0;
1649
1650                 if (old_technology->compatible) {
1651                         is_compatible = old_technology->compatible(bridge);
1652                 } else if (old_technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX) {
1653                         is_compatible = 1;
1654                 } else if (bridge->num_channels <= 2
1655                         && (old_technology->capabilities & AST_BRIDGE_CAPABILITY_1TO1MIX)) {
1656                         is_compatible = 1;
1657                 }
1658
1659                 if (is_compatible) {
1660                         ast_debug(1, "Bridge %s could not get a new technology, staying with old technology.\n",
1661                                 bridge->uniqueid);
1662                         return 0;
1663                 }
1664                 ast_log(LOG_WARNING, "Bridge %s has no technology available to support it.\n",
1665                         bridge->uniqueid);
1666                 return -1;
1667         }
1668         if (new_technology == old_technology) {
1669                 ast_debug(1, "Bridge %s is already using the new technology.\n",
1670                         bridge->uniqueid);
1671                 ast_module_unref(old_technology->mod);
1672                 return 0;
1673         }
1674
1675         ast_copy_string(dummy_bridge.uniqueid, bridge->uniqueid, sizeof(dummy_bridge.uniqueid));
1676
1677         if (old_technology->destroy) {
1678                 struct tech_deferred_destroy deferred_tech_destroy = {
1679                         .tech = dummy_bridge.technology,
1680                         .tech_pvt = dummy_bridge.tech_pvt,
1681                 };
1682                 struct ast_frame action = {
1683                         .frametype = AST_FRAME_BRIDGE_ACTION,
1684                         .subclass.integer = AST_BRIDGE_ACTION_DEFERRED_TECH_DESTROY,
1685                         .data.ptr = &deferred_tech_destroy,
1686                         .datalen = sizeof(deferred_tech_destroy),
1687                 };
1688
1689                 /*
1690                  * We need to defer the bridge technology destroy callback
1691                  * because we have the bridge locked.
1692                  */
1693                 deferred_action = ast_frdup(&action);
1694                 if (!deferred_action) {
1695                         ast_module_unref(new_technology->mod);
1696                         return -1;
1697                 }
1698         } else {
1699                 deferred_action = NULL;
1700         }
1701
1702         /*
1703          * We are now committed to changing the bridge technology.  We
1704          * must not release the bridge lock until we have installed the
1705          * new bridge technology.
1706          */
1707         ast_debug(1, "Bridge %s: switching %s technology to %s\n",
1708                 bridge->uniqueid, old_technology->name, new_technology->name);
1709
1710         /*
1711          * Since we are soon going to pass this bridge to a new
1712          * technology we need to NULL out the tech_pvt pointer but
1713          * don't worry as it still exists in dummy_bridge, ditto for the
1714          * old technology.
1715          */
1716         bridge->tech_pvt = NULL;
1717         bridge->technology = new_technology;
1718
1719         /* Setup the new bridge technology. */
1720         ast_debug(1, "Bridge %s: calling %s technology constructor\n",
1721                 bridge->uniqueid, new_technology->name);
1722         if (new_technology->create && new_technology->create(bridge)) {
1723                 ast_log(LOG_WARNING, "Bridge %s: failed to setup bridge technology %s\n",
1724                         bridge->uniqueid, new_technology->name);
1725                 bridge->tech_pvt = dummy_bridge.tech_pvt;
1726                 bridge->technology = dummy_bridge.technology;
1727                 ast_module_unref(new_technology->mod);
1728                 return -1;
1729         }
1730
1731         /* Move existing channels over to the new technology. */
1732         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1733                 if (bridge_channel->just_joined) {
1734                         /*
1735                          * This channel has not completed joining the bridge so it is
1736                          * not in the old bridge technology.
1737                          */
1738                         continue;
1739                 }
1740
1741                 /* First we part them from the old technology */
1742                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology (dummy)\n",
1743                         dummy_bridge.uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1744                         old_technology->name);
1745                 if (old_technology->leave) {
1746                         old_technology->leave(&dummy_bridge, bridge_channel);
1747                 }
1748
1749                 /* Second we make them compatible again with the bridge */
1750                 bridge_make_compatible(bridge, bridge_channel);
1751
1752                 /* Third we join them to the new technology */
1753                 ast_debug(1, "Bridge %s: %p(%s) is joining %s technology\n",
1754                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1755                         new_technology->name);
1756                 if (new_technology->join && new_technology->join(bridge, bridge_channel)) {
1757                         ast_debug(1, "Bridge %s: %p(%s) failed to join %s technology\n",
1758                                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1759                                 new_technology->name);
1760                 }
1761         }
1762
1763         /*
1764          * Now that all the channels have been moved over we need to get
1765          * rid of all the information the old technology may have left
1766          * around.
1767          */
1768         if (old_technology->destroy) {
1769                 ast_debug(1, "Bridge %s: deferring %s technology destructor\n",
1770                         bridge->uniqueid, old_technology->name);
1771                 bridge_queue_action_nodup(bridge, deferred_action);
1772         } else {
1773                 ast_debug(1, "Bridge %s: calling %s technology destructor\n",
1774                         bridge->uniqueid, old_technology->name);
1775                 ast_module_unref(old_technology->mod);
1776         }
1777
1778         return 0;
1779 }
1780
1781 /*!
1782  * \internal
1783  * \brief Bridge channel to check if a BRIDGE_PLAY_SOUND needs to be played.
1784  * \since 12.0.0
1785  *
1786  * \param bridge_channel What to check.
1787  *
1788  * \return Nothing
1789  */
1790 static void check_bridge_play_sound(struct ast_bridge_channel *bridge_channel)
1791 {
1792         const char *play_file;
1793
1794         ast_channel_lock(bridge_channel->chan);
1795         play_file = pbx_builtin_getvar_helper(bridge_channel->chan, "BRIDGE_PLAY_SOUND");
1796         if (!ast_strlen_zero(play_file)) {
1797                 play_file = ast_strdupa(play_file);
1798                 pbx_builtin_setvar_helper(bridge_channel->chan, "BRIDGE_PLAY_SOUND", NULL);
1799         } else {
1800                 play_file = NULL;
1801         }
1802         ast_channel_unlock(bridge_channel->chan);
1803
1804         if (play_file) {
1805                 ast_bridge_channel_queue_playfile(bridge_channel, NULL, play_file, NULL);
1806         }
1807 }
1808
1809 /*!
1810  * \internal
1811  * \brief Check for any BRIDGE_PLAY_SOUND channel variables in the bridge.
1812  * \since 12.0.0
1813  *
1814  * \param bridge What to operate on.
1815  *
1816  * \note On entry, the bridge is already locked.
1817  *
1818  * \return Nothing
1819  */
1820 static void check_bridge_play_sounds(struct ast_bridge *bridge)
1821 {
1822         struct ast_bridge_channel *bridge_channel;
1823
1824         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1825                 check_bridge_play_sound(bridge_channel);
1826         }
1827 }
1828
1829 static void update_bridge_vars_set(struct ast_channel *chan, const char *name, const char *pvtid)
1830 {
1831         pbx_builtin_setvar_helper(chan, "BRIDGEPEER", name);
1832         pbx_builtin_setvar_helper(chan, "BRIDGEPVTCALLID", pvtid);
1833 }
1834
1835 /*!
1836  * \internal
1837  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a 2 party bridge.
1838  * \since 12.0.0
1839  *
1840  * \param c0 Party of the first part.
1841  * \param c1 Party of the second part.
1842  *
1843  * \note On entry, the bridge is already locked.
1844  * \note The bridge is expected to have exactly two parties.
1845  *
1846  * \return Nothing
1847  */
1848 static void set_bridge_peer_vars_2party(struct ast_channel *c0, struct ast_channel *c1)
1849 {
1850         const char *c0_name;
1851         const char *c1_name;
1852         const char *c0_pvtid = NULL;
1853         const char *c1_pvtid = NULL;
1854 #define UPDATE_BRIDGE_VARS_GET(chan, name, pvtid)                                                                       \
1855         do {                                                                                                                                                    \
1856                 name = ast_strdupa(ast_channel_name(chan));                                                                     \
1857                 if (ast_channel_tech(chan)->get_pvt_uniqueid) {                                                         \
1858                         pvtid = ast_strdupa(ast_channel_tech(chan)->get_pvt_uniqueid(chan));    \
1859                 }                                                                                                                                                       \
1860         } while (0)
1861
1862         ast_channel_lock(c1);
1863         UPDATE_BRIDGE_VARS_GET(c1, c1_name, c1_pvtid);
1864         ast_channel_unlock(c1);
1865
1866         ast_channel_lock(c0);
1867         update_bridge_vars_set(c0, c1_name, c1_pvtid);
1868         UPDATE_BRIDGE_VARS_GET(c0, c0_name, c0_pvtid);
1869         ast_channel_unlock(c0);
1870
1871         ast_channel_lock(c1);
1872         update_bridge_vars_set(c1, c0_name, c0_pvtid);
1873         ast_channel_unlock(c1);
1874 }
1875
1876 /*!
1877  * \internal
1878  * \brief Fill the BRIDGEPEER value buffer with a comma separated list of channel names.
1879  * \since 12.0.0
1880  *
1881  * \param buf Buffer to fill.  The caller must guarantee the buffer is large enough.
1882  * \param cur_idx Which index into names[] to skip.
1883  * \param names Channel names to put in the buffer.
1884  * \param num_names Number of names in the array.
1885  *
1886  * \return Nothing
1887  */
1888 static void fill_bridgepeer_buf(char *buf, unsigned int cur_idx, const char *names[], unsigned int num_names)
1889 {
1890         int need_separator = 0;
1891         unsigned int idx;
1892         const char *src;
1893         char *pos;
1894
1895         pos = buf;
1896         for (idx = 0; idx < num_names; ++idx) {
1897                 if (idx == cur_idx) {
1898                         continue;
1899                 }
1900
1901                 if (need_separator) {
1902                         *pos++ = ',';
1903                 }
1904                 need_separator = 1;
1905
1906                 /* Copy name into buffer. */
1907                 src = names[idx];
1908                 while (*src) {
1909                         *pos++ = *src++;
1910                 }
1911         }
1912         *pos = '\0';
1913 }
1914
1915 /*!
1916  * \internal
1917  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a multi-party bridge.
1918  * \since 12.0.0
1919  *
1920  * \param bridge What to operate on.
1921  *
1922  * \note On entry, the bridge is already locked.
1923  * \note The bridge is expected to have more than two parties.
1924  *
1925  * \return Nothing
1926  */
1927 static void set_bridge_peer_vars_multiparty(struct ast_bridge *bridge)
1928 {
1929 /*
1930  * Set a maximum number of channel names for the BRIDGEPEER
1931  * list.  The plus one is for the current channel which is not
1932  * put in the list.
1933  */
1934 #define MAX_BRIDGEPEER_CHANS    (10 + 1)
1935
1936         unsigned int idx;
1937         unsigned int num_names;
1938         unsigned int len;
1939         const char **names;
1940         char *buf;
1941         struct ast_bridge_channel *bridge_channel;
1942
1943         /* Get first MAX_BRIDGEPEER_CHANS channel names. */
1944         num_names = MIN(bridge->num_channels, MAX_BRIDGEPEER_CHANS);
1945         names = ast_alloca(num_names * sizeof(*names));
1946         idx = 0;
1947         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1948                 if (num_names <= idx) {
1949                         break;
1950                 }
1951                 ast_channel_lock(bridge_channel->chan);
1952                 names[idx++] = ast_strdupa(ast_channel_name(bridge_channel->chan));
1953                 ast_channel_unlock(bridge_channel->chan);
1954         }
1955
1956         /* Determine maximum buf size needed. */
1957         len = num_names;
1958         for (idx = 0; idx < num_names; ++idx) {
1959                 len += strlen(names[idx]);
1960         }
1961         buf = ast_alloca(len);
1962
1963         /* Set the bridge channel variables. */
1964         idx = 0;
1965         buf[0] = '\0';
1966         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1967                 if (idx < num_names) {
1968                         fill_bridgepeer_buf(buf, idx, names, num_names);
1969                 }
1970                 ++idx;
1971
1972                 ast_channel_lock(bridge_channel->chan);
1973                 update_bridge_vars_set(bridge_channel->chan, buf, NULL);
1974                 ast_channel_unlock(bridge_channel->chan);
1975         }
1976 }
1977
1978 /*!
1979  * \internal
1980  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a holding bridge.
1981  * \since 12.0.0
1982  *
1983  * \param bridge What to operate on.
1984  *
1985  * \note On entry, the bridge is already locked.
1986  *
1987  * \return Nothing
1988  */
1989 static void set_bridge_peer_vars_holding(struct ast_bridge *bridge)
1990 {
1991         struct ast_bridge_channel *bridge_channel;
1992
1993         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1994                 ast_channel_lock(bridge_channel->chan);
1995                 update_bridge_vars_set(bridge_channel->chan, NULL, NULL);
1996                 ast_channel_unlock(bridge_channel->chan);
1997         }
1998 }
1999
2000 /*!
2001  * \internal
2002  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in the bridge.
2003  * \since 12.0.0
2004  *
2005  * \param bridge What to operate on.
2006  *
2007  * \note On entry, the bridge is already locked.
2008  *
2009  * \return Nothing
2010  */
2011 static void set_bridge_peer_vars(struct ast_bridge *bridge)
2012 {
2013         if (bridge->technology->capabilities & AST_BRIDGE_CAPABILITY_HOLDING) {
2014                 set_bridge_peer_vars_holding(bridge);
2015                 return;
2016         }
2017         if (bridge->num_channels < 2) {
2018                 return;
2019         }
2020         if (bridge->num_channels == 2) {
2021                 set_bridge_peer_vars_2party(AST_LIST_FIRST(&bridge->channels)->chan,
2022                         AST_LIST_LAST(&bridge->channels)->chan);
2023         } else {
2024                 set_bridge_peer_vars_multiparty(bridge);
2025         }
2026 }
2027
2028 /*!
2029  * \internal
2030  * \brief Notify the bridge that it has been reconfigured.
2031  * \since 12.0.0
2032  *
2033  * \param bridge Reconfigured bridge.
2034  *
2035  * \details
2036  * After a series of bridge_channel_push and
2037  * bridge_channel_pull calls, you need to call this function
2038  * to cause the bridge to complete restruturing for the change
2039  * in the channel makeup of the bridge.
2040  *
2041  * \note On entry, the bridge is already locked.
2042  *
2043  * \return Nothing
2044  */
2045 static void bridge_reconfigured(struct ast_bridge *bridge)
2046 {
2047         if (!bridge->reconfigured) {
2048                 return;
2049         }
2050         bridge->reconfigured = 0;
2051         if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_SMART)
2052                 && smart_bridge_operation(bridge)) {
2053                 /* Smart bridge failed. */
2054                 bridge_dissolve(bridge);
2055                 return;
2056         }
2057         bridge_complete_join(bridge);
2058
2059         if (bridge->dissolved) {
2060                 return;
2061         }
2062         check_bridge_play_sounds(bridge);
2063         set_bridge_peer_vars(bridge);
2064 }
2065
2066 /*!
2067  * \internal
2068  * \brief Suspend a channel from a bridge.
2069  *
2070  * \param bridge_channel Channel to suspend.
2071  *
2072  * \note This function assumes bridge_channel->bridge is locked.
2073  *
2074  * \return Nothing
2075  */
2076 static void bridge_channel_suspend_nolock(struct ast_bridge_channel *bridge_channel)
2077 {
2078         bridge_channel->suspended = 1;
2079         if (bridge_channel->in_bridge) {
2080                 --bridge_channel->bridge->num_active;
2081         }
2082
2083         /* Get technology bridge threads off of the channel. */
2084         if (bridge_channel->bridge->technology->suspend) {
2085                 bridge_channel->bridge->technology->suspend(bridge_channel->bridge, bridge_channel);
2086         }
2087 }
2088
2089 /*!
2090  * \internal
2091  * \brief Suspend a channel from a bridge.
2092  *
2093  * \param bridge_channel Channel to suspend.
2094  *
2095  * \return Nothing
2096  */
2097 static void bridge_channel_suspend(struct ast_bridge_channel *bridge_channel)
2098 {
2099         ast_bridge_channel_lock_bridge(bridge_channel);
2100         bridge_channel_suspend_nolock(bridge_channel);
2101         ast_bridge_unlock(bridge_channel->bridge);
2102 }
2103
2104 /*!
2105  * \internal
2106  * \brief Unsuspend a channel from a bridge.
2107  *
2108  * \param bridge_channel Channel to unsuspend.
2109  *
2110  * \note This function assumes bridge_channel->bridge is locked.
2111  *
2112  * \return Nothing
2113  */
2114 static void bridge_channel_unsuspend_nolock(struct ast_bridge_channel *bridge_channel)
2115 {
2116         bridge_channel->suspended = 0;
2117         if (bridge_channel->in_bridge) {
2118                 ++bridge_channel->bridge->num_active;
2119         }
2120
2121         /* Wake technology bridge threads to take care of channel again. */
2122         if (bridge_channel->bridge->technology->unsuspend) {
2123                 bridge_channel->bridge->technology->unsuspend(bridge_channel->bridge, bridge_channel);
2124         }
2125
2126         /* Wake suspended channel. */
2127         ast_bridge_channel_lock(bridge_channel);
2128         ast_cond_signal(&bridge_channel->cond);
2129         ast_bridge_channel_unlock(bridge_channel);
2130 }
2131
2132 /*!
2133  * \internal
2134  * \brief Unsuspend a channel from a bridge.
2135  *
2136  * \param bridge_channel Channel to unsuspend.
2137  *
2138  * \return Nothing
2139  */
2140 static void bridge_channel_unsuspend(struct ast_bridge_channel *bridge_channel)
2141 {
2142         ast_bridge_channel_lock_bridge(bridge_channel);
2143         bridge_channel_unsuspend_nolock(bridge_channel);
2144         ast_bridge_unlock(bridge_channel->bridge);
2145 }
2146
2147 /*! \brief Internal function that activates interval hooks on a bridge channel */
2148 static void bridge_channel_interval(struct ast_bridge_channel *bridge_channel)
2149 {
2150         struct ast_bridge_hook *hook;
2151         struct timeval start;
2152
2153         ast_heap_wrlock(bridge_channel->features->interval_hooks);
2154         start = ast_tvnow();
2155         while ((hook = ast_heap_peek(bridge_channel->features->interval_hooks, 1))) {
2156                 int interval;
2157                 unsigned int execution_time;
2158
2159                 if (ast_tvdiff_ms(hook->parms.timer.trip_time, start) > 0) {
2160                         ast_debug(1, "Hook %p on %p(%s) wants to happen in the future, stopping our traversal\n",
2161                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
2162                         break;
2163                 }
2164                 ao2_ref(hook, +1);
2165                 ast_heap_unlock(bridge_channel->features->interval_hooks);
2166
2167                 ast_debug(1, "Executing hook %p on %p(%s)\n",
2168                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
2169                 interval = hook->callback(bridge_channel->bridge, bridge_channel, hook->hook_pvt);
2170
2171                 ast_heap_wrlock(bridge_channel->features->interval_hooks);
2172                 if (ast_heap_peek(bridge_channel->features->interval_hooks,
2173                         hook->parms.timer.heap_index) != hook
2174                         || !ast_heap_remove(bridge_channel->features->interval_hooks, hook)) {
2175                         /* Interval hook is already removed from the bridge_channel. */
2176                         ao2_ref(hook, -1);
2177                         continue;
2178                 }
2179                 ao2_ref(hook, -1);
2180
2181                 if (interval < 0) {
2182                         ast_debug(1, "Removed interval hook %p from %p(%s)\n",
2183                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
2184                         ao2_ref(hook, -1);
2185                         continue;
2186                 }
2187                 if (interval) {
2188                         /* Set new interval for the hook. */
2189                         hook->parms.timer.interval = interval;
2190                 }
2191
2192                 ast_debug(1, "Updating interval hook %p with interval %u on %p(%s)\n",
2193                         hook, hook->parms.timer.interval, bridge_channel,
2194                         ast_channel_name(bridge_channel->chan));
2195
2196                 /* resetting start */
2197                 start = ast_tvnow();
2198
2199                 /*
2200                  * Resetup the interval hook for the next interval.  We may need
2201                  * to skip over any missed intervals because the hook was
2202                  * delayed or took too long.
2203                  */
2204                 execution_time = ast_tvdiff_ms(start, hook->parms.timer.trip_time);
2205                 while (hook->parms.timer.interval < execution_time) {
2206                         execution_time -= hook->parms.timer.interval;
2207                 }
2208                 hook->parms.timer.trip_time = ast_tvadd(start, ast_samp2tv(hook->parms.timer.interval - execution_time, 1000));
2209                 hook->parms.timer.seqno = ast_atomic_fetchadd_int((int *) &bridge_channel->features->interval_sequence, +1);
2210
2211                 if (ast_heap_push(bridge_channel->features->interval_hooks, hook)) {
2212                         /* Could not push the hook back onto the heap. */
2213                         ao2_ref(hook, -1);
2214                 }
2215         }
2216         ast_heap_unlock(bridge_channel->features->interval_hooks);
2217 }
2218
2219 static void bridge_channel_write_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
2220 {
2221         ast_bridge_channel_write_action_data(bridge_channel,
2222                 AST_BRIDGE_ACTION_DTMF_STREAM, dtmf, strlen(dtmf) + 1);
2223 }
2224
2225 /*!
2226  * \brief Internal function that executes a feature on a bridge channel
2227  * \note Neither the bridge nor the bridge_channel locks should be held when entering
2228  * this function.
2229  */
2230 static void bridge_channel_feature(struct ast_bridge_channel *bridge_channel)
2231 {
2232         struct ast_bridge_features *features = bridge_channel->features;
2233         struct ast_bridge_hook *hook = NULL;
2234         char dtmf[MAXIMUM_DTMF_FEATURE_STRING] = "";
2235         size_t dtmf_len = 0;
2236         unsigned int digit_timeout;
2237         RAII_VAR(struct ast_features_general_config *, gen_cfg, NULL, ao2_cleanup);
2238
2239         ast_channel_lock(bridge_channel->chan);
2240         gen_cfg = ast_get_chan_features_general_config(bridge_channel->chan);
2241         if (!gen_cfg) {
2242                 ast_log(LOG_ERROR, "Unable to retrieve features configuration.\n");
2243                 ast_channel_unlock(bridge_channel->chan);
2244                 return;
2245         }
2246         digit_timeout = gen_cfg->featuredigittimeout;
2247         ast_channel_unlock(bridge_channel->chan);
2248
2249         /* The channel is now under our control and we don't really want any begin frames to do our DTMF matching so disable 'em at the core level */
2250         ast_set_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_END_DTMF_ONLY);
2251
2252         /* Wait for DTMF on the channel and put it into a buffer. If the buffer matches any feature hook execute the hook. */
2253         do {
2254                 int res;
2255
2256                 /* If the above timed out simply exit */
2257                 res = ast_waitfordigit(bridge_channel->chan, digit_timeout);
2258                 if (!res) {
2259                         ast_debug(1, "DTMF feature string collection on %p(%s) timed out\n",
2260                                 bridge_channel, ast_channel_name(bridge_channel->chan));
2261                         break;
2262                 }
2263                 if (res < 0) {
2264                         ast_debug(1, "DTMF feature string collection failed on %p(%s) for some reason\n",
2265                                 bridge_channel, ast_channel_name(bridge_channel->chan));
2266                         break;
2267                 }
2268
2269 /* BUGBUG need to record the duration of DTMF digits so when the string is played back, they are reproduced. */
2270                 /* Add the above DTMF into the DTMF string so we can do our matching */
2271                 dtmf[dtmf_len++] = res;
2272                 ast_debug(1, "DTMF feature string on %p(%s) is now '%s'\n",
2273                         bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
2274
2275                 /* See if a DTMF feature hook matches or can match */
2276                 hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
2277                 if (!hook) {
2278                         ast_debug(1, "No DTMF feature hooks on %p(%s) match '%s'\n",
2279                                 bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
2280                         break;
2281                 }
2282                 if (strlen(hook->parms.dtmf.code) == dtmf_len) {
2283                         ast_debug(1, "DTMF feature hook %p matched DTMF string '%s' on %p(%s)\n",
2284                                 hook, dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
2285                         break;
2286                 }
2287                 ao2_ref(hook, -1);
2288                 hook = NULL;
2289
2290                 /* Stop if we have reached the maximum length of a DTMF feature string. */
2291         } while (dtmf_len < ARRAY_LEN(dtmf) - 1);
2292
2293         /* Since we are done bringing DTMF in return to using both begin and end frames */
2294         ast_clear_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_END_DTMF_ONLY);
2295
2296         /* If a hook was actually matched execute it on this channel, otherwise stream up the DTMF to the other channels */
2297         if (hook) {
2298                 int failed;
2299
2300                 failed = hook->callback(bridge_channel->bridge, bridge_channel, hook->hook_pvt);
2301                 if (failed) {
2302                         ast_debug(1, "DTMF hook %p is being removed from %p(%s)\n",
2303                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
2304                         ao2_unlink(features->dtmf_hooks, hook);
2305                 }
2306                 ao2_ref(hook, -1);
2307
2308                 /*
2309                  * If we are handing the channel off to an external hook for
2310                  * ownership, we are not guaranteed what kind of state it will
2311                  * come back in.  If the channel hungup, we need to detect that
2312                  * here if the hook did not already change the state.
2313                  */
2314                 if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
2315                         bridge_handle_hangup(bridge_channel);
2316                 }
2317         } else if (features->dtmf_passthrough) {
2318                 bridge_channel_write_dtmf_stream(bridge_channel, dtmf);
2319         }
2320 }
2321
2322 static void bridge_channel_talking(struct ast_bridge_channel *bridge_channel, int talking)
2323 {
2324         struct ast_bridge_features *features = bridge_channel->features;
2325
2326         if (features->talker_cb) {
2327                 features->talker_cb(bridge_channel, features->talker_pvt_data, talking);
2328         }
2329 }
2330
2331 /*! \brief Internal function that plays back DTMF on a bridge channel */
2332 static void bridge_channel_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
2333 {
2334         ast_debug(1, "Playing DTMF stream '%s' out to %p(%s)\n",
2335                 dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
2336         ast_dtmf_stream(bridge_channel->chan, NULL, dtmf, 0, 0);
2337 }
2338
2339 struct blind_transfer_data {
2340         char exten[AST_MAX_EXTENSION];
2341         char context[AST_MAX_CONTEXT];
2342 };
2343
2344 static void bridge_channel_blind_transfer(struct ast_bridge_channel *bridge_channel,
2345                 struct blind_transfer_data *blind_data)
2346 {
2347         ast_async_goto(bridge_channel->chan, blind_data->context, blind_data->exten, 1);
2348         bridge_handle_hangup(bridge_channel);
2349 }
2350
2351 static void after_bridge_move_channel(struct ast_channel *chan_bridged, void *data)
2352 {
2353         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
2354
2355         if (ast_channel_move(chan_target, chan_bridged)) {
2356                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
2357         }
2358 }
2359
2360 static void after_bridge_move_channel_fail(enum ast_after_bridge_cb_reason reason, void *data)
2361 {
2362         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
2363
2364         ast_log(LOG_WARNING, "Unable to complete transfer: %s\n",
2365                 ast_after_bridge_cb_reason_string(reason));
2366         ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
2367 }
2368
2369 static void bridge_channel_attended_transfer(struct ast_bridge_channel *bridge_channel,
2370                 const char *target_chan_name)
2371 {
2372         RAII_VAR(struct ast_channel *, chan_target, NULL, ao2_cleanup);
2373         RAII_VAR(struct ast_channel *, chan_bridged, NULL, ao2_cleanup);
2374
2375         chan_target = ast_channel_get_by_name(target_chan_name);
2376         if (!chan_target) {
2377                 /* Dang, it disappeared somehow */
2378                 bridge_handle_hangup(bridge_channel);
2379                 return;
2380         }
2381
2382         ast_bridge_channel_lock(bridge_channel);
2383         chan_bridged = bridge_channel->chan;
2384         ast_assert(chan_bridged != NULL);
2385         ao2_ref(chan_bridged, +1);
2386         ast_bridge_channel_unlock(bridge_channel);
2387
2388         if (ast_after_bridge_callback_set(chan_bridged, after_bridge_move_channel,
2389                 after_bridge_move_channel_fail, ast_channel_ref(chan_target))) {
2390                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
2391
2392                 /* Release the ref we tried to pass to ast_after_bridge_callback_set(). */
2393                 ast_channel_unref(chan_target);
2394         }
2395         bridge_handle_hangup(bridge_channel);
2396 }
2397
2398 /*!
2399  * \internal
2400  * \brief Handle bridge channel bridge action frame.
2401  * \since 12.0.0
2402  *
2403  * \param bridge_channel Channel to execute the action on.
2404  * \param action What to do.
2405  *
2406  * \return Nothing
2407  */
2408 static void bridge_channel_handle_action(struct ast_bridge_channel *bridge_channel, struct ast_frame *action)
2409 {
2410         switch (action->subclass.integer) {
2411         case AST_BRIDGE_ACTION_INTERVAL:
2412                 bridge_channel_suspend(bridge_channel);
2413                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2414                 bridge_channel_interval(bridge_channel);
2415                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2416                 bridge_channel_unsuspend(bridge_channel);
2417                 break;
2418         case AST_BRIDGE_ACTION_FEATURE:
2419                 bridge_channel_suspend(bridge_channel);
2420                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2421                 bridge_channel_feature(bridge_channel);
2422                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2423                 bridge_channel_unsuspend(bridge_channel);
2424                 break;
2425         case AST_BRIDGE_ACTION_DTMF_STREAM:
2426                 bridge_channel_suspend(bridge_channel);
2427                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2428                 bridge_channel_dtmf_stream(bridge_channel, action->data.ptr);
2429                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2430                 bridge_channel_unsuspend(bridge_channel);
2431                 break;
2432         case AST_BRIDGE_ACTION_TALKING_START:
2433         case AST_BRIDGE_ACTION_TALKING_STOP:
2434                 bridge_channel_talking(bridge_channel,
2435                         action->subclass.integer == AST_BRIDGE_ACTION_TALKING_START);
2436                 break;
2437         case AST_BRIDGE_ACTION_PLAY_FILE:
2438                 bridge_channel_suspend(bridge_channel);
2439                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2440                 bridge_channel_playfile(bridge_channel, action->data.ptr);
2441                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2442                 bridge_channel_unsuspend(bridge_channel);
2443                 break;
2444         case AST_BRIDGE_ACTION_RUN_APP:
2445                 bridge_channel_suspend(bridge_channel);
2446                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2447                 bridge_channel_run_app(bridge_channel, action->data.ptr);
2448                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2449                 bridge_channel_unsuspend(bridge_channel);
2450                 break;
2451         case AST_BRIDGE_ACTION_CALLBACK:
2452                 bridge_channel_suspend(bridge_channel);
2453                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2454                 bridge_channel_do_callback(bridge_channel, action->data.ptr);
2455                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2456                 bridge_channel_unsuspend(bridge_channel);
2457                 break;
2458         case AST_BRIDGE_ACTION_PARK:
2459                 bridge_channel_suspend(bridge_channel);
2460                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2461                 bridge_channel_park(bridge_channel, action->data.ptr);
2462                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2463                 bridge_channel_unsuspend(bridge_channel);
2464                 break;
2465         case AST_BRIDGE_ACTION_BLIND_TRANSFER:
2466                 bridge_channel_blind_transfer(bridge_channel, action->data.ptr);
2467                 break;
2468         case AST_BRIDGE_ACTION_ATTENDED_TRANSFER:
2469                 bridge_channel_attended_transfer(bridge_channel, action->data.ptr);
2470                 break;
2471         default:
2472                 break;
2473         }
2474 }
2475
2476 /*!
2477  * \internal
2478  * \brief Handle bridge channel control frame action.
2479  * \since 12.0.0
2480  *
2481  * \param bridge_channel Channel to execute the control frame action on.
2482  * \param fr Control frame to handle.
2483  *
2484  * \return Nothing
2485  */
2486 static void bridge_channel_handle_control(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
2487 {
2488         struct ast_channel *chan;
2489         struct ast_option_header *aoh;
2490         int is_caller;
2491         int intercept_failed;
2492
2493         chan = bridge_channel->chan;
2494         switch (fr->subclass.integer) {
2495         case AST_CONTROL_REDIRECTING:
2496                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2497                 bridge_channel_suspend(bridge_channel);
2498                 intercept_failed = ast_channel_redirecting_sub(NULL, chan, fr, 1)
2499                         && ast_channel_redirecting_macro(NULL, chan, fr, is_caller, 1);
2500                 bridge_channel_unsuspend(bridge_channel);
2501                 if (intercept_failed) {
2502                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2503                 }
2504                 break;
2505         case AST_CONTROL_CONNECTED_LINE:
2506                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2507                 bridge_channel_suspend(bridge_channel);
2508                 intercept_failed = ast_channel_connected_line_sub(NULL, chan, fr, 1)
2509                         && ast_channel_connected_line_macro(NULL, chan, fr, is_caller, 1);
2510                 bridge_channel_unsuspend(bridge_channel);
2511                 if (intercept_failed) {
2512                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2513                 }
2514                 break;
2515         case AST_CONTROL_HOLD:
2516         case AST_CONTROL_UNHOLD:
2517 /*
2518  * BUGBUG bridge_channels should remember sending/receiving an outstanding HOLD to/from the bridge
2519  *
2520  * When the sending channel is pulled from the bridge it needs to write into the bridge an UNHOLD before being pulled.
2521  * When the receiving channel is pulled from the bridge it needs to generate its own UNHOLD.
2522  * Something similar needs to be done for DTMF begin/end.
2523  */
2524         case AST_CONTROL_VIDUPDATE:
2525         case AST_CONTROL_SRCUPDATE:
2526         case AST_CONTROL_SRCCHANGE:
2527         case AST_CONTROL_T38_PARAMETERS:
2528 /* BUGBUG may have to do something with a jitter buffer for these. */
2529                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2530                 break;
2531         case AST_CONTROL_OPTION:
2532                 /*
2533                  * Forward option Requests, but only ones we know are safe These
2534                  * are ONLY sent by chan_iax2 and I'm not convinced that they
2535                  * are useful. I haven't deleted them entirely because I just am
2536                  * not sure of the ramifications of removing them.
2537                  */
2538                 aoh = fr->data.ptr;
2539                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
2540                         switch (ntohs(aoh->option)) {
2541                         case AST_OPTION_TONE_VERIFY:
2542                         case AST_OPTION_TDD:
2543                         case AST_OPTION_RELAXDTMF:
2544                         case AST_OPTION_AUDIO_MODE:
2545                         case AST_OPTION_DIGIT_DETECT:
2546                         case AST_OPTION_FAX_DETECT:
2547                                 ast_channel_setoption(chan, ntohs(aoh->option), aoh->data,
2548                                         fr->datalen - sizeof(*aoh), 0);
2549                                 break;
2550                         default:
2551                                 break;
2552                         }
2553                 }
2554                 break;
2555         case AST_CONTROL_ANSWER:
2556                 if (ast_channel_state(chan) != AST_STATE_UP) {
2557                         ast_answer(chan);
2558                 } else {
2559                         ast_indicate(chan, -1);
2560                 }
2561                 break;
2562         default:
2563                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2564                 break;
2565         }
2566 }
2567
2568 /*!
2569  * \internal
2570  * \brief Handle bridge channel write frame to channel.
2571  * \since 12.0.0
2572  *
2573  * \param bridge_channel Channel to write outgoing frame.
2574  *
2575  * \return Nothing
2576  */
2577 static void bridge_channel_handle_write(struct ast_bridge_channel *bridge_channel)
2578 {
2579         struct ast_frame *fr;
2580         char nudge;
2581
2582         ast_bridge_channel_lock(bridge_channel);
2583         if (read(bridge_channel->alert_pipe[0], &nudge, sizeof(nudge)) < 0) {
2584                 if (errno != EINTR && errno != EAGAIN) {
2585                         ast_log(LOG_WARNING, "read() failed for alert pipe on %p(%s): %s\n",
2586                                 bridge_channel, ast_channel_name(bridge_channel->chan), strerror(errno));
2587                 }
2588         }
2589         fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list);
2590         ast_bridge_channel_unlock(bridge_channel);
2591         if (!fr) {
2592                 return;
2593         }
2594         switch (fr->frametype) {
2595         case AST_FRAME_BRIDGE_ACTION:
2596                 bridge_channel_handle_action(bridge_channel, fr);
2597                 break;
2598         case AST_FRAME_CONTROL:
2599                 bridge_channel_handle_control(bridge_channel, fr);
2600                 break;
2601         case AST_FRAME_NULL:
2602                 break;
2603         default:
2604                 /* Write the frame to the channel. */
2605                 bridge_channel->activity = AST_BRIDGE_CHANNEL_THREAD_SIMPLE;
2606                 ast_write(bridge_channel->chan, fr);
2607                 break;
2608         }
2609         ast_frfree(fr);
2610 }
2611
2612 /*!
2613  * \internal
2614  * \brief Handle bridge channel interval expiration.
2615  * \since 12.0.0
2616  *
2617  * \param bridge_channel Channel to check interval on.
2618  *
2619  * \return Nothing
2620  */
2621 static void bridge_channel_handle_interval(struct ast_bridge_channel *bridge_channel)
2622 {
2623         struct ast_timer *interval_timer;
2624
2625         interval_timer = bridge_channel->features->interval_timer;
2626         if (interval_timer) {
2627                 if (ast_wait_for_input(ast_timer_fd(interval_timer), 0) == 1) {
2628                         ast_timer_ack(interval_timer, 1);
2629                         if (bridge_channel_interval_ready(bridge_channel)) {
2630 /* BUGBUG since this is now only run by the channel thread, there is no need to queue the action once this intervals become a first class wait item in bridge_channel_wait(). */
2631                                 struct ast_frame interval_action = {
2632                                         .frametype = AST_FRAME_BRIDGE_ACTION,
2633                                         .subclass.integer = AST_BRIDGE_ACTION_INTERVAL,
2634                                 };
2635
2636                                 ast_bridge_channel_queue_frame(bridge_channel, &interval_action);
2637                         }
2638                 }
2639         }
2640 }
2641
2642 /*!
2643  * \internal
2644  * \brief Wait for something to happen on the bridge channel and handle it.
2645  * \since 12.0.0
2646  *
2647  * \param bridge_channel Channel to wait.
2648  *
2649  * \note Each channel does writing/reading in their own thread.
2650  *
2651  * \return Nothing
2652  */
2653 static void bridge_channel_wait(struct ast_bridge_channel *bridge_channel)
2654 {
2655         int ms = -1;
2656         int outfd;
2657         struct ast_channel *chan;
2658
2659         /* Wait for data to either come from the channel or us to be signaled */
2660         ast_bridge_channel_lock(bridge_channel);
2661         if (bridge_channel->state != AST_BRIDGE_CHANNEL_STATE_WAIT) {
2662         } else if (bridge_channel->suspended) {
2663 /* BUGBUG the external party use of suspended will go away as will these references because this is the bridge channel thread */
2664                 ast_debug(1, "Bridge %s: %p(%s) is going into a signal wait\n",
2665                         bridge_channel->bridge->uniqueid, bridge_channel,
2666                         ast_channel_name(bridge_channel->chan));
2667                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
2668         } else {
2669                 ast_debug(10, "Bridge %s: %p(%s) is going into a waitfor\n",
2670                         bridge_channel->bridge->uniqueid, bridge_channel,
2671                         ast_channel_name(bridge_channel->chan));
2672                 bridge_channel->waiting = 1;
2673                 ast_bridge_channel_unlock(bridge_channel);
2674                 outfd = -1;
2675 /* BUGBUG need to make the next expiring active interval setup ms timeout rather than holding up the chan reads. */
2676                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1,
2677                         &bridge_channel->alert_pipe[0], 1, NULL, &outfd, &ms);
2678                 bridge_channel->waiting = 0;
2679                 if (ast_channel_softhangup_internal_flag(bridge_channel->chan) & AST_SOFTHANGUP_UNBRIDGE) {
2680                         ast_channel_clear_softhangup(bridge_channel->chan, AST_SOFTHANGUP_UNBRIDGE);
2681                         ast_bridge_channel_lock_bridge(bridge_channel);
2682                         bridge_channel->bridge->reconfigured = 1;
2683                         bridge_reconfigured(bridge_channel->bridge);
2684                         ast_bridge_unlock(bridge_channel->bridge);
2685                 }
2686                 ast_bridge_channel_lock(bridge_channel);
2687                 bridge_channel->activity = AST_BRIDGE_CHANNEL_THREAD_FRAME;
2688                 ast_bridge_channel_unlock(bridge_channel);
2689                 if (!bridge_channel->suspended
2690                         && bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
2691                         if (chan) {
2692                                 bridge_channel_handle_interval(bridge_channel);
2693                                 bridge_handle_trip(bridge_channel);
2694                         } else if (-1 < outfd) {
2695                                 bridge_channel_handle_write(bridge_channel);
2696                         }
2697                 }
2698                 bridge_channel->activity = AST_BRIDGE_CHANNEL_THREAD_IDLE;
2699                 return;
2700         }
2701         ast_bridge_channel_unlock(bridge_channel);
2702 }
2703
2704 /*!
2705  * \internal
2706  * \brief Handle bridge channel join event.
2707  * \since 12.0.0
2708  *
2709  * \param bridge_channel Which channel is joining.
2710  *
2711  * \return Nothing
2712  */
2713 static void bridge_channel_handle_join(struct ast_bridge_channel *bridge_channel)
2714 {
2715         struct ast_bridge_features *features = bridge_channel->features;
2716         struct ast_bridge_hook *hook;
2717         struct ao2_iterator iter;
2718
2719         /* Run any join hooks. */
2720         iter = ao2_iterator_init(features->join_hooks, AO2_ITERATOR_UNLINK);
2721         hook = ao2_iterator_next(&iter);
2722         if (hook) {
2723                 bridge_channel_suspend(bridge_channel);
2724                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2725                 do {
2726                         hook->callback(bridge_channel->bridge, bridge_channel, hook->hook_pvt);
2727                         ao2_ref(hook, -1);
2728                 } while ((hook = ao2_iterator_next(&iter)));
2729                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2730                 bridge_channel_unsuspend(bridge_channel);
2731         }
2732         ao2_iterator_destroy(&iter);
2733 }
2734
2735 /*!
2736  * \internal
2737  * \brief Handle bridge channel leave event.
2738  * \since 12.0.0
2739  *
2740  * \param bridge_channel Which channel is leaving.
2741  *
2742  * \return Nothing
2743  */
2744 static void bridge_channel_handle_leave(struct ast_bridge_channel *bridge_channel)
2745 {
2746         struct ast_bridge_features *features = bridge_channel->features;
2747         struct ast_bridge_hook *hook;
2748         struct ao2_iterator iter;
2749
2750         /* Run any leave hooks. */
2751         iter = ao2_iterator_init(features->leave_hooks, AO2_ITERATOR_UNLINK);
2752         hook = ao2_iterator_next(&iter);
2753         if (hook) {
2754                 bridge_channel_suspend(bridge_channel);
2755                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2756                 do {
2757                         hook->callback(bridge_channel->bridge, bridge_channel, hook->hook_pvt);
2758                         ao2_ref(hook, -1);
2759                 } while ((hook = ao2_iterator_next(&iter)));
2760                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2761                 bridge_channel_unsuspend(bridge_channel);
2762         }
2763         ao2_iterator_destroy(&iter);
2764 }
2765
2766 /*! \brief Join a channel to a bridge and handle anything the bridge may want us to do */
2767 static void bridge_channel_join(struct ast_bridge_channel *bridge_channel)
2768 {
2769         ast_format_copy(&bridge_channel->read_format, ast_channel_readformat(bridge_channel->chan));
2770         ast_format_copy(&bridge_channel->write_format, ast_channel_writeformat(bridge_channel->chan));
2771
2772         ast_debug(1, "Bridge %s: %p(%s) is joining\n",
2773                 bridge_channel->bridge->uniqueid,
2774                 bridge_channel, ast_channel_name(bridge_channel->chan));
2775
2776         /*
2777          * Get "in the bridge" before pushing the channel for any
2778          * masquerades on the channel to happen before bridging.
2779          */
2780         ast_channel_lock(bridge_channel->chan);
2781         ast_channel_internal_bridge_set(bridge_channel->chan, bridge_channel->bridge);
2782         ast_channel_unlock(bridge_channel->chan);
2783
2784         /* Add the jitterbuffer if the channel requires it */
2785         ast_jb_enable_for_channel(bridge_channel->chan);
2786
2787         /*
2788          * Directly locking the bridge is safe here because nobody else
2789          * knows about this bridge_channel yet.
2790          */
2791         ast_bridge_lock(bridge_channel->bridge);
2792
2793         if (!bridge_channel->bridge->callid) {
2794                 bridge_channel->bridge->callid = ast_read_threadstorage_callid();
2795         }
2796
2797         if (bridge_channel_push(bridge_channel)) {
2798                 ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
2799         }
2800         bridge_reconfigured(bridge_channel->bridge);
2801
2802         if (bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
2803                 /*
2804                  * Indicate a source change since this channel is entering the
2805                  * bridge system only if the bridge technology is not MULTIMIX
2806                  * capable.  The MULTIMIX technology has already done it.
2807                  */
2808                 if (!(bridge_channel->bridge->technology->capabilities
2809                         & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
2810                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2811                 }
2812
2813                 ast_bridge_unlock(bridge_channel->bridge);
2814                 bridge_channel_handle_join(bridge_channel);
2815                 while (bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
2816                         /* Wait for something to do. */
2817                         bridge_channel_wait(bridge_channel);
2818                 }
2819                 bridge_channel_handle_leave(bridge_channel);
2820                 ast_bridge_channel_lock_bridge(bridge_channel);
2821         }
2822
2823         bridge_channel_pull(bridge_channel);
2824         bridge_reconfigured(bridge_channel->bridge);
2825
2826         ast_bridge_unlock(bridge_channel->bridge);
2827
2828         /* Indicate a source change since this channel is leaving the bridge system. */
2829         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2830
2831 /* BUGBUG Revisit in regards to moving channels between bridges and local channel optimization. */
2832 /* BUGBUG This is where outgoing HOLD/UNHOLD memory should write UNHOLD to channel. */
2833         /* Complete any partial DTMF digit before exiting the bridge. */
2834         if (ast_channel_sending_dtmf_digit(bridge_channel->chan)) {
2835                 ast_bridge_end_dtmf(bridge_channel->chan,
2836                         ast_channel_sending_dtmf_digit(bridge_channel->chan),
2837                         ast_channel_sending_dtmf_tv(bridge_channel->chan), "bridge end");
2838         }
2839
2840         /*
2841          * Wait for any dual redirect to complete.
2842          *
2843          * Must be done while "still in the bridge" for ast_async_goto()
2844          * to work right.
2845          */
2846         while (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT)) {
2847                 sched_yield();
2848         }
2849         ast_channel_lock(bridge_channel->chan);
2850         ast_channel_internal_bridge_set(bridge_channel->chan, NULL);
2851         ast_channel_unlock(bridge_channel->chan);
2852
2853         ast_bridge_channel_restore_formats(bridge_channel);
2854 }
2855
2856 /*!
2857  * \internal
2858  * \brief Close a pipe.
2859  * \since 12.0.0
2860  *
2861  * \param my_pipe What to close.
2862  *
2863  * \return Nothing
2864  */
2865 static void pipe_close(int *my_pipe)
2866 {
2867         if (my_pipe[0] > -1) {
2868                 close(my_pipe[0]);
2869                 my_pipe[0] = -1;
2870         }
2871         if (my_pipe[1] > -1) {
2872                 close(my_pipe[1]);
2873                 my_pipe[1] = -1;
2874         }
2875 }
2876
2877 /*!
2878  * \internal
2879  * \brief Initialize a pipe as non-blocking.
2880  * \since 12.0.0
2881  *
2882  * \param my_pipe What to initialize.
2883  *
2884  * \retval 0 on success.
2885  * \retval -1 on error.
2886  */
2887 static int pipe_init_nonblock(int *my_pipe)
2888 {
2889         int flags;
2890
2891         my_pipe[0] = -1;
2892         my_pipe[1] = -1;
2893         if (pipe(my_pipe)) {
2894                 ast_log(LOG_WARNING, "Can't create pipe! Try increasing max file descriptors with ulimit -n\n");
2895                 return -1;
2896         }
2897         flags = fcntl(my_pipe[0], F_GETFL);
2898         if (fcntl(my_pipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2899                 ast_log(LOG_WARNING, "Unable to set read pipe nonblocking! (%d: %s)\n",
2900                         errno, strerror(errno));
2901                 return -1;
2902         }
2903         flags = fcntl(my_pipe[1], F_GETFL);
2904         if (fcntl(my_pipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
2905                 ast_log(LOG_WARNING, "Unable to set write pipe nonblocking! (%d: %s)\n",
2906                         errno, strerror(errno));
2907                 return -1;
2908         }
2909         return 0;
2910 }
2911
2912 /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
2913 static void bridge_channel_destroy(void *obj)
2914 {
2915         struct ast_bridge_channel *bridge_channel = obj;
2916         struct ast_frame *fr;
2917
2918         if (bridge_channel->callid) {
2919                 bridge_channel->callid = ast_callid_unref(bridge_channel->callid);
2920         }
2921
2922         if (bridge_channel->bridge) {
2923                 ao2_ref(bridge_channel->bridge, -1);
2924                 bridge_channel->bridge = NULL;
2925         }
2926
2927         /* Flush any unhandled wr_queue frames. */
2928         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list))) {
2929                 ast_frfree(fr);
2930         }
2931         pipe_close(bridge_channel->alert_pipe);
2932
2933         ast_cond_destroy(&bridge_channel->cond);
2934 }
2935
2936 static struct ast_bridge_channel *bridge_channel_alloc(struct ast_bridge *bridge)
2937 {
2938         struct ast_bridge_channel *bridge_channel;
2939
2940         bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
2941         if (!bridge_channel) {
2942                 return NULL;
2943         }
2944         ast_cond_init(&bridge_channel->cond, NULL);
2945         if (pipe_init_nonblock(bridge_channel->alert_pipe)) {
2946                 ao2_ref(bridge_channel, -1);
2947                 return NULL;
2948         }
2949         if (bridge) {
2950                 bridge_channel->bridge = bridge;
2951                 ao2_ref(bridge_channel->bridge, +1);
2952         }
2953
2954         return bridge_channel;
2955 }
2956
2957 struct after_bridge_cb_ds {
2958         /*! Desired callback function. */
2959         ast_after_bridge_cb callback;
2960         /*! After bridge callback will not be called and destroy any resources data may contain. */
2961         ast_after_bridge_cb_failed failed;
2962         /*! Extra data to pass to the callback. */
2963         void *data;
2964 };
2965
2966 /*!
2967  * \internal
2968  * \brief Destroy the after bridge callback datastore.
2969  * \since 12.0.0
2970  *
2971  * \param data After bridge callback data to destroy.
2972  *
2973  * \return Nothing
2974  */
2975 static void after_bridge_cb_destroy(void *data)
2976 {
2977         struct after_bridge_cb_ds *after_bridge = data;
2978
2979         if (after_bridge->failed) {
2980                 after_bridge->failed(AST_AFTER_BRIDGE_CB_REASON_DESTROY, after_bridge->data);
2981                 after_bridge->failed = NULL;
2982         }
2983 }
2984
2985 /*!
2986  * \internal
2987  * \brief Fixup the after bridge callback datastore.
2988  * \since 12.0.0
2989  *
2990  * \param data After bridge callback data to fixup.
2991  * \param old_chan The datastore is moving from this channel.
2992  * \param new_chan The datastore is moving to this channel.
2993  *
2994  * \return Nothing
2995  */
2996 static void after_bridge_cb_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan)
2997 {
2998         /* There can be only one.  Discard any already on the new channel. */
2999         ast_after_bridge_callback_discard(new_chan, AST_AFTER_BRIDGE_CB_REASON_MASQUERADE);
3000 }
3001
3002 static const struct ast_datastore_info after_bridge_cb_info = {
3003         .type = "after-bridge-cb",
3004         .destroy = after_bridge_cb_destroy,
3005         .chan_fixup = after_bridge_cb_fixup,
3006 };
3007
3008 /*!
3009  * \internal
3010  * \brief Remove channel after the bridge callback and return it.
3011  * \since 12.0.0
3012  *
3013  * \param chan Channel to remove after bridge callback.
3014  *
3015  * \retval datastore on success.
3016  * \retval NULL on error or not found.
3017  */
3018 static struct ast_datastore *after_bridge_cb_remove(struct ast_channel *chan)
3019 {
3020         struct ast_datastore *datastore;
3021
3022         ast_channel_lock(chan);
3023         datastore = ast_channel_datastore_find(chan, &after_bridge_cb_info, NULL);
3024         if (datastore && ast_channel_datastore_remove(chan, datastore)) {
3025                 datastore = NULL;
3026         }
3027         ast_channel_unlock(chan);
3028
3029         return datastore;
3030 }
3031
3032 void ast_after_bridge_callback_discard(struct ast_channel *chan, enum ast_after_bridge_cb_reason reason)
3033 {
3034         struct ast_datastore *datastore;
3035
3036         datastore = after_bridge_cb_remove(chan);
3037         if (datastore) {
3038                 struct after_bridge_cb_ds *after_bridge = datastore->data;
3039
3040                 if (after_bridge && after_bridge->failed) {
3041                         after_bridge->failed(reason, after_bridge->data);
3042                         after_bridge->failed = NULL;
3043                 }
3044                 ast_datastore_free(datastore);
3045         }
3046 }
3047
3048 /*!
3049  * \internal
3050  * \brief Run any after bridge callback if possible.
3051  * \since 12.0.0
3052  *
3053  * \param chan Channel to run after bridge callback.
3054  *
3055  * \return Nothing
3056  */
3057 static void after_bridge_callback_run(struct ast_channel *chan)
3058 {
3059         struct ast_datastore *datastore;
3060         struct after_bridge_cb_ds *after_bridge;
3061
3062         if (ast_check_hangup(chan)) {
3063                 return;
3064         }
3065
3066         /* Get after bridge goto datastore. */
3067         datastore = after_bridge_cb_remove(chan);
3068         if (!datastore) {
3069                 return;
3070         }
3071
3072         after_bridge = datastore->data;
3073         if (after_bridge) {
3074                 after_bridge->failed = NULL;
3075                 after_bridge->callback(chan, after_bridge->data);
3076         }
3077
3078         /* Discard after bridge callback datastore. */
3079         ast_datastore_free(datastore);
3080 }
3081
3082 int ast_after_bridge_callback_set(struct ast_channel *chan, ast_after_bridge_cb callback, ast_after_bridge_cb_failed failed, void *data)
3083 {
3084         struct ast_datastore *datastore;
3085         struct after_bridge_cb_ds *after_bridge;
3086
3087         /* Sanity checks. */
3088         ast_assert(chan != NULL);
3089         if (!chan || !callback) {
3090                 return -1;
3091         }
3092
3093         /* Create a new datastore. */
3094         datastore = ast_datastore_alloc(&after_bridge_cb_info, NULL);
3095         if (!datastore) {
3096                 return -1;
3097         }
3098         after_bridge = ast_calloc(1, sizeof(*after_bridge));
3099         if (!after_bridge) {
3100                 ast_datastore_free(datastore);
3101                 return -1;
3102         }
3103
3104         /* Initialize it. */
3105         after_bridge->callback = callback;
3106         after_bridge->failed = failed;
3107         after_bridge->data = data;
3108         datastore->data = after_bridge;
3109
3110         /* Put it on the channel replacing any existing one. */
3111         ast_channel_lock(chan);
3112         ast_after_bridge_callback_discard(chan, AST_AFTER_BRIDGE_CB_REASON_REPLACED);
3113         ast_channel_datastore_add(chan, datastore);
3114         ast_channel_unlock(chan);
3115
3116         return 0;
3117 }
3118
3119 const char *reason_strings[] = {
3120         [AST_AFTER_BRIDGE_CB_REASON_DESTROY] = "Bridge Destroyed",
3121         [AST_AFTER_BRIDGE_CB_REASON_REPLACED] = "Channel replaced",
3122         [AST_AFTER_BRIDGE_CB_REASON_MASQUERADE] = "Channel masqueraded",
3123         [AST_AFTER_BRIDGE_CB_REASON_DEPART] = "Channel departed",
3124         [AST_AFTER_BRIDGE_CB_REASON_REMOVED] = "Channel removed",
3125 };
3126
3127 const char *ast_after_bridge_cb_reason_string(enum ast_after_bridge_cb_reason reason)
3128 {
3129         if (reason < AST_AFTER_BRIDGE_CB_REASON_DESTROY || reason > AST_AFTER_BRIDGE_CB_REASON_REMOVED) {
3130                 return "Unknown";
3131         }
3132
3133         return reason_strings[reason];
3134 }
3135
3136 struct after_bridge_goto_ds {
3137         /*! Goto string that can be parsed by ast_parseable_goto(). */
3138         const char *parseable_goto;
3139         /*! Specific goto context or default context for parseable_goto. */
3140         const char *context;
3141         /*! Specific goto exten or default exten for parseable_goto. */
3142         const char *exten;
3143         /*! Specific goto priority or default priority for parseable_goto. */
3144         int priority;
3145         /*! TRUE if the peer should run the h exten. */
3146         unsigned int run_h_exten:1;
3147         /*! Specific goto location */
3148         unsigned int specific:1;
3149 };
3150
3151 /*!
3152  * \internal
3153  * \brief Destroy the after bridge goto datastore.
3154  * \since 12.0.0
3155  *
3156  * \param data After bridge goto data to destroy.
3157  *
3158  * \return Nothing
3159  */
3160 static void after_bridge_goto_destroy(void *data)
3161 {
3162         struct after_bridge_goto_ds *after_bridge = data;
3163
3164         ast_free((char *) after_bridge->parseable_goto);
3165         ast_free((char *) after_bridge->context);
3166         ast_free((char *) after_bridge->exten);
3167 }
3168
3169 /*!
3170  * \internal
3171  * \brief Fixup the after bridge goto datastore.
3172  * \since 12.0.0
3173  *
3174  * \param data After bridge goto data to fixup.
3175  * \param old_chan The datastore is moving from this channel.
3176  * \param new_chan The datastore is moving to this channel.
3177  *
3178  * \return Nothing
3179  */
3180 static void after_bridge_goto_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan)
3181 {
3182         /* There can be only one.  Discard any already on the new channel. */
3183         ast_after_bridge_goto_discard(new_chan);
3184 }
3185
3186 static const struct ast_datastore_info after_bridge_goto_info = {
3187         .type = "after-bridge-goto",
3188         .destroy = after_bridge_goto_destroy,
3189         .chan_fixup = after_bridge_goto_fixup,
3190 };
3191
3192 /*!
3193  * \internal
3194  * \brief Remove channel goto location after the bridge and return it.
3195  * \since 12.0.0
3196  *
3197  * \param chan Channel to remove after bridge goto location.
3198  *
3199  * \retval datastore on success.
3200  * \retval NULL on error or not found.
3201  */
3202 static struct ast_datastore *after_bridge_goto_remove(struct ast_channel *chan)
3203 {
3204         struct ast_datastore *datastore;
3205
3206         ast_channel_lock(chan);
3207         datastore = ast_channel_datastore_find(chan, &after_bridge_goto_info, NULL);
3208         if (datastore && ast_channel_datastore_remove(chan, datastore)) {
3209                 datastore = NULL;
3210         }
3211         ast_channel_unlock(chan);
3212
3213         return datastore;
3214 }
3215
3216 void ast_after_bridge_goto_discard(struct ast_channel *chan)
3217 {
3218         struct ast_datastore *datastore;
3219
3220         datastore = after_bridge_goto_remove(chan);
3221         if (datastore) {
3222                 ast_datastore_free(datastore);
3223         }
3224 }
3225
3226 int ast_after_bridge_goto_setup(struct ast_channel *chan)
3227 {
3228         struct ast_datastore *datastore;
3229         struct after_bridge_goto_ds *after_bridge;
3230         int goto_failed = -1;
3231
3232         /* Determine if we are going to setup a dialplan location and where. */
3233         if (ast_channel_softhangup_internal_flag(chan) & AST_SOFTHANGUP_ASYNCGOTO) {
3234                 /* An async goto has already setup a location. */
3235                 ast_channel_clear_softhangup(chan, AST_SOFTHANGUP_ASYNCGOTO);
3236                 if (!ast_check_hangup(chan)) {
3237                         goto_failed = 0;
3238                 }
3239                 return goto_failed;
3240         }
3241
3242         /* Get after bridge goto datastore. */
3243         datastore = after_bridge_goto_remove(chan);
3244         if (!datastore) {
3245                 return goto_failed;
3246         }
3247
3248         after_bridge = datastore->data;
3249         if (after_bridge->run_h_exten) {
3250                 if (ast_exists_extension(chan, after_bridge->context, "h", 1,
3251                         S_COR(ast_channel_caller(chan)->id.number.valid,
3252                                 ast_channel_caller(chan)->id.number.str, NULL))) {
3253                         ast_debug(1, "Running after bridge goto h exten %s,h,1\n",
3254                                 ast_channel_context(chan));
3255                         ast_pbx_h_exten_run(chan, after_bridge->context);
3256                 }
3257         } else if (!ast_check_hangup(chan)) {
3258                 if (after_bridge->specific) {
3259                         goto_failed = ast_explicit_goto(chan, after_bridge->context,
3260                                 after_bridge->exten, after_bridge->priority);
3261                 } else if (!ast_strlen_zero(after_bridge->parseable_goto)) {
3262                         char *context;
3263                         char *exten;
3264                         int priority;
3265
3266                         /* Option F(x) for Bridge(), Dial(), and Queue() */
3267
3268                         /* Save current dialplan location in case of failure. */
3269                         context = ast_strdupa(ast_channel_context(chan));
3270                         exten = ast_strdupa(ast_channel_exten(chan));
3271                         priority = ast_channel_priority(chan);
3272
3273                         /* Set current dialplan position to default dialplan position */
3274                         ast_explicit_goto(chan, after_bridge->context, after_bridge->exten,
3275                                 after_bridge->priority);
3276
3277                         /* Then perform the goto */
3278                         goto_failed = ast_parseable_goto(chan, after_bridge->parseable_goto);
3279                         if (goto_failed) {
3280                                 /* Restore original dialplan location. */
3281                                 ast_channel_context_set(chan, context);
3282                                 ast_channel_exten_set(chan, exten);
3283                                 ast_channel_priority_set(chan, priority);
3284                         }
3285                 } else {
3286                         /* Option F() for Bridge(), Dial(), and Queue() */
3287                         goto_failed = ast_goto_if_exists(chan, after_bridge->context,
3288                                 after_bridge->exten, after_bridge->priority + 1);
3289                 }
3290                 if (!goto_failed) {
3291                         ast_debug(1, "Setup after bridge goto location to %s,%s,%d.\n",
3292                                 ast_channel_context(chan),
3293                                 ast_channel_exten(chan),
3294                                 ast_channel_priority(chan));
3295                 }
3296         }
3297
3298         /* Discard after bridge goto datastore. */
3299         ast_datastore_free(datastore);
3300
3301         return goto_failed;
3302 }
3303
3304 void ast_after_bridge_goto_run(struct ast_channel *chan)
3305 {
3306         int goto_failed;
3307
3308         goto_failed = ast_after_bridge_goto_setup(chan);
3309         if (goto_failed || ast_pbx_run(chan)) {
3310                 ast_hangup(chan);
3311         }
3312 }
3313
3314 /*!
3315  * \internal
3316  * \brief Set after bridge goto location of channel.
3317  * \since 12.0.0
3318  *
3319  * \param chan Channel to setup after bridge goto location.
3320  * \param run_h_exten TRUE if the h exten should be run.
3321  * \param specific TRUE if the context/exten/priority is exactly specified.
3322  * \param context Context to goto after bridge.
3323  * \param exten Exten to goto after bridge. (Could be NULL if run_h_exten)
3324  * \param priority Priority to goto after bridge.
3325  * \param parseable_goto User specified goto string. (Could be NULL)
3326  *
3327  * \details Add a channel datastore to setup the goto location
3328  * when the channel leaves the bridge and run a PBX from there.
3329  *
3330  * If run_h_exten then execute the h exten found in the given context.
3331  * Else if specific then goto the given context/exten/priority.
3332  * Else if parseable_goto then use the given context/exten/priority
3333  *   as the relative position for the parseable_goto.
3334  * Else goto the given context/exten/priority+1.
3335  *
3336  * \return Nothing
3337  */
3338 static void __after_bridge_set_goto(struct ast_channel *chan, int run_h_exten, int specific, const char *context, const char *exten, int priority, const char *parseable_goto)
3339 {
3340         struct ast_datastore *datastore;
3341         struct after_bridge_goto_ds *after_bridge;
3342
3343         /* Sanity checks. */
3344         ast_assert(chan != NULL);
3345         if (!chan) {
3346                 return;
3347         }
3348         if (run_h_exten) {
3349                 ast_assert(run_h_exten && context);
3350                 if (!context) {
3351                         return;
3352                 }
3353         } else {
3354                 ast_assert(context && exten && 0 < priority);
3355                 if (!context || !exten || priority < 1) {
3356                         return;
3357                 }
3358         }
3359
3360         /* Create a new datastore. */
3361         datastore = ast_datastore_alloc(&after_bridge_goto_info, NULL);
3362         if (!datastore) {
3363                 return;
3364         }
3365         after_bridge = ast_calloc(1, sizeof(*after_bridge));
3366         if (!after_bridge) {
3367                 ast_datastore_free(datastore);
3368                 return;
3369         }
3370
3371         /* Initialize it. */
3372         after_bridge->parseable_goto = ast_strdup(parseable_goto);
3373         after_bridge->context = ast_strdup(context);
3374         after_bridge->exten = ast_strdup(exten);
3375         after_bridge->priority = priority;
3376         after_bridge->run_h_exten = run_h_exten ? 1 : 0;
3377         after_bridge->specific = specific ? 1 : 0;
3378         datastore->data = after_bridge;
3379         if ((parseable_goto && !after_bridge->parseable_goto)
3380                 || (context && !after_bridge->context)
3381                 || (exten && !after_bridge->exten)) {
3382                 ast_datastore_free(datastore);
3383                 return;
3384         }
3385
3386         /* Put it on the channel replacing any existing one. */
3387         ast_channel_lock(chan);
3388         ast_after_bridge_goto_discard(chan);
3389         ast_channel_datastore_add(chan, datastore);
3390         ast_channel_unlock(chan);
3391 }
3392
3393 void ast_after_bridge_set_goto(struct ast_channel *chan, const char *context, const char *exten, int priority)
3394 {
3395         __after_bridge_set_goto(chan, 0, 1, context, exten, priority, NULL);
3396 }
3397
3398 void ast_after_bridge_set_h(struct ast_channel *chan, const char *context)
3399 {
3400         __after_bridge_set_goto(chan, 1, 0, context, NULL, 1, NULL);
3401 }
3402
3403 void ast_after_bridge_set_go_on(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *parseable_goto)
3404 {
3405         char *p_goto;
3406
3407         if (!ast_strlen_zero(parseable_goto)) {
3408                 p_goto = ast_strdupa(parseable_goto);
3409                 ast_replace_subargument_delimiter(p_goto);
3410         } else {
3411                 p_goto = NULL;
3412         }
3413         __after_bridge_set_goto(chan, 0, 0, context, exten, priority, p_goto);
3414 }
3415
3416 void ast_bridge_notify_masquerade(struct ast_channel *chan)
3417 {
3418         struct ast_bridge_channel *bridge_channel;
3419         struct ast_bridge *bridge;
3420
3421         /* Safely get the bridge_channel pointer for the chan. */
3422         ast_channel_lock(chan);
3423         bridge_channel = ast_channel_get_bridge_channel(chan);
3424         ast_channel_unlock(chan);
3425         if (!bridge_channel) {
3426                 /* Not in a bridge */
3427                 return;
3428         }
3429
3430         ast_bridge_channel_lock_bridge(bridge_channel);
3431         bridge = bridge_channel->bridge;
3432         if (bridge_channel == find_bridge_channel(bridge, chan)) {
3433 /* BUGBUG this needs more work.  The channels need to be made compatible again if the formats change. The bridge_channel thread needs to monitor for this case. */
3434                 /* The channel we want to notify is still in a bridge. */
3435                 bridge->v_table->notify_masquerade(bridge, bridge_channel);
3436                 bridge_reconfigured(bridge);
3437         }
3438         ast_bridge_unlock(bridge);
3439         ao2_ref(bridge_channel, -1);
3440 }
3441
3442 /*
3443  * BUGBUG make ast_bridge_join() require features to be allocated just like ast_bridge_impart() and not expect the struct back.
3444  *
3445  * This change is really going to break ConfBridge.  All other
3446  * users are easily changed.  However, it is needed so the
3447  * bridging code can manipulate features on all channels
3448  * consistently no matter how they joined.
3449  *
3450  * Need to update the features parameter doxygen when this
3451  * change is made to be like ast_bridge_impart().
3452  */
3453 enum ast_bridge_channel_state ast_bridge_join(struct ast_bridge *bridge,
3454         struct ast_channel *chan,
3455         struct ast_channel *swap,
3456         struct ast_bridge_features *features,
3457         struct ast_bridge_tech_optimizations *tech_args,
3458         int pass_reference)
3459 {
3460         struct ast_bridge_channel *bridge_channel;
3461         enum ast_bridge_channel_state state;
3462
3463         bridge_channel = bridge_channel_alloc(bridge);
3464         if (pass_reference) {
3465                 ao2_ref(bridge, -1);
3466         }
3467         if (!bridge_channel) {
3468                 state = AST_BRIDGE_CHANNEL_STATE_HANGUP;
3469                 goto join_exit;
3470         }
3471 /* BUGBUG features cannot be NULL when passed in. When it is changed to allocated we can do like ast_bridge_impart() and allocate one. */
3472         ast_assert(features != NULL);
3473         if (!features) {
3474                 ao2_ref(bridge_channel, -1);
3475                 state = AST_BRIDGE_CHANNEL_STATE_HANGUP;
3476                 goto join_exit;
3477         }
3478         if (tech_args) {
3479                 bridge_channel->tech_args = *tech_args;
3480         }
3481
3482         /* Initialize various other elements of the bridge channel structure that we can't do above */
3483         ast_channel_lock(chan);
3484         ast_channel_internal_bridge_channel_set(chan, bridge_channel);
3485         ast_channel_unlock(chan);
3486         bridge_channel->thread = pthread_self();
3487         bridge_channel->chan = chan;
3488         bridge_channel->swap = swap;
3489         bridge_channel->features = features;
3490
3491         bridge_channel_join(bridge_channel);
3492         state = bridge_channel->state;
3493
3494         /* Cleanup all the data in the bridge channel after it leaves the bridge. */
3495         ast_channel_lock(chan);
3496         ast_channel_internal_bridge_channel_set(chan, NULL);
3497         ast_channel_unlock(chan);
3498         bridge_channel->chan = NULL;
3499         bridge_channel->swap = NULL;
3500         bridge_channel->features = NULL;
3501
3502         ao2_ref(bridge_channel, -1);
3503
3504 join_exit:;
3505 /* BUGBUG this is going to cause problems for DTMF atxfer attended bridge between B & C.  Maybe an ast_bridge_join_internal() that does not do the after bridge goto for this case. */
3506         after_bridge_callback_run(chan);
3507         if (!(ast_channel_softhangup_internal_flag(chan) & AST_SOFTHANGUP_ASYNCGOTO)
3508                 && !ast_after_bridge_goto_setup(chan)) {
3509                 /* Claim the after bridge goto is an async goto destination. */
3510                 ast_channel_lock(chan);
3511                 ast_softhangup_nolock(chan, AST_SOFTHANGUP_ASYNCGOTO);
3512                 ast_channel_unlock(chan);
3513         }
3514         return state;
3515 }
3516
3517 /*! \brief Thread responsible for imparted bridged channels to be departed */
3518 static void *bridge_channel_depart_thread(void *data)
3519 {
3520         struct ast_bridge_channel *bridge_channel = data;
3521
3522         if (bridge_channel->callid) {
3523                 ast_callid_threadassoc_add(bridge_channel->callid);
3524         }
3525
3526         bridge_channel_join(bridge_channel);
3527
3528         /* cleanup */
3529         bridge_channel->swap = NULL;
3530         ast_bridge_features_destroy(bridge_channel->features);
3531         bridge_channel->features = NULL;
3532
3533         ast_after_bridge_callback_discard(bridge_channel->chan, AST_AFTER_BRIDGE_CB_REASON_DEPART);
3534         ast_after_bridge_goto_discard(bridge_channel->chan);
3535
3536         return NULL;
3537 }
3538
3539 /*! \brief Thread responsible for independent imparted bridged channels */
3540 static void *bridge_channel_ind_thread(void *data)
3541 {
3542         struct ast_bridge_channel *bridge_channel = data;
3543         struct ast_channel *chan;
3544
3545         if (bridge_channel->callid) {
3546                 ast_callid_threadassoc_add(bridge_channel->callid);
3547         }
3548
3549         bridge_channel_join(bridge_channel);
3550         chan = bridge_channel->chan;
3551
3552         /* cleanup */
3553         ast_channel_lock(chan);
3554         ast_channel_internal_bridge_channel_set(chan, NULL);
3555         ast_channel_unlock(chan);
3556         bridge_channel->chan = NULL;
3557         bridge_channel->swap = NULL;
3558         ast_bridge_features_destroy(bridge_channel->features);
3559         bridge_channel->features = NULL;
3560
3561         ao2_ref(bridge_channel, -1);
3562
3563         after_bridge_callback_run(chan);
3564         ast_after_bridge_goto_run(chan);
3565         return NULL;
3566 }
3567
3568 int ast_bridge_impart(struct ast_bridge *bridge, struct ast_channel *chan, struct ast_channel *swap, struct ast_bridge_features *features, int independent)
3569 {
3570         int res;
3571         struct ast_bridge_channel *bridge_channel;
3572
3573         /* Supply an empty features structure if the caller did not. */
3574         if (!features) {
3575                 features = ast_bridge_features_new();
3576                 if (!features) {
3577                         return -1;
3578                 }
3579         }
3580
3581         /* Try to allocate a structure for the bridge channel */
3582         bridge_channel = bridge_channel_alloc(bridge);
3583         if (!bridge_channel) {
3584                 ast_bridge_features_destroy(features);
3585                 return -1;
3586         }
3587
3588         /* Setup various parameters */
3589         ast_channel_lock(chan);
3590         ast_channel_internal_bridge_channel_set(chan, bridge_channel);
3591         ast_channel_unlock(chan);
3592         bridge_channel->chan = chan;
3593         bridge_channel->swap = swap;
3594         bridge_channel->features = features;
3595         bridge_channel->depart_wait = independent ? 0 : 1;
3596         bridge_channel->callid = ast_read_threadstorage_callid();
3597
3598         /* Actually create the thread that will handle the channel */
3599         if (independent) {
3600                 /* Independently imparted channels cannot have a PBX. */
3601                 ast_assert(!ast_channel_pbx(chan));
3602
3603                 res = ast_pthread_create_detached(&bridge_channel->thread, NULL,
3604                         bridge_channel_ind_thread, bridge_channel);
3605         } else {
3606                 /* Imparted channels to be departed should not have a PBX either. */
3607                 ast_assert(!ast_channel_pbx(chan));
3608
3609                 res = ast_pthread_create(&bridge_channel->thread, NULL,
3610                         bridge_channel_depart_thread, bridge_channel);
3611         }
3612
3613         if (res) {
3614                 /* cleanup */
3615                 ast_channel_lock(chan);
3616                 ast_channel_internal_bridge_channel_set(chan, NULL);
3617                 ast_channel_unlock(chan);
3618                 bridge_channel->chan = NULL;
3619                 bridge_channel->swap = NULL;
3620                 ast_bridge_features_destroy(bridge_channel->features);
3621                 bridge_channel->features = NULL;
3622
3623                 ao2_ref(bridge_channel, -1);
3624                 return -1;
3625         }
3626
3627         return 0;
3628 }
3629
3630 int ast_bridge_depart(struct ast_channel *chan)
3631 {
3632         struct ast_bridge_channel *bridge_channel;
3633         int departable;
3634
3635         ast_channel_lock(chan);
3636         bridge_channel = ast_channel_internal_bridge_channel(chan);
3637         departable = bridge_channel && bridge_channel->depart_wait;
3638         ast_channel_unlock(chan);
3639         if (!departable) {
3640                 ast_log(LOG_ERROR, "Channel %s cannot be departed.\n",
3641                         ast_channel_name(chan));
3642                 /*
3643                  * Should never happen.  It likely means that
3644                  * ast_bridge_depart() is called by two threads for the same
3645                  * channel, the channel was never imparted to be departed, or it
3646                  * has already been departed.
3647                  */
3648                 ast_assert(0);
3649                 return -1;
3650         }
3651
3652         /*
3653          * We are claiming the reference held by the depart bridge
3654          * channel thread.
3655          */
3656
3657         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
3658
3659         /* Wait for the depart thread to die */
3660         ast_debug(1, "Waiting for %p(%s) bridge thread to die.\n",
3661                 bridge_channel, ast_channel_name(bridge_channel->chan));
3662         pthread_join(bridge_channel->thread, NULL);
3663
3664         ast_channel_lock(chan);
3665         ast_channel_internal_bridge_channel_set(chan, NULL);
3666         ast_channel_unlock(chan);
3667
3668         /* We can get rid of the bridge_channel after the depart thread has died. */
3669         ao2_ref(bridge_channel, -1);
3670         return 0;
3671 }
3672
3673 int ast_bridge_remove(struct ast_bridge *bridge, struct ast_channel *chan)
3674 {
3675         struct ast_bridge_channel *bridge_channel;
3676
3677         ast_bridge_lock(bridge);
3678
3679         /* Try to find the channel that we want to remove */
3680         if (!(bridge_channel = find_bridge_channel(bridge, chan))) {
3681                 ast_bridge_unlock(bridge);
3682                 return -1;
3683         }
3684
3685         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
3686
3687         ast_bridge_unlock(bridge);
3688
3689         return 0;
3690 }
3691
3692 /*!
3693  * \internal
3694  * \brief Point the bridge_channel to a new bridge.
3695  * \since 12.0.0
3696  *
3697  * \param bridge_channel What is to point to a new bridge.
3698  * \param new_bridge Where the bridge channel should point.
3699  *
3700  * \return Nothing
3701  */
3702 static void bridge_channel_change_bridge(struct ast_bridge_channel *bridge_channel, struct ast_bridge *new_bridge)
3703 {
3704         struct ast_bridge *old_bridge;
3705
3706         ao2_ref(new_bridge, +1);
3707         ast_bridge_channel_lock(bridge_channel);
3708         ast_channel_lock(bridge_channel->chan);
3709         old_bridge = bridge_channel->bridge;
3710         bridge_channel->bridge = new_bridge;
3711         ast_channel_internal_bridge_set(bridge_channel->chan, new_bridge);
3712         ast_channel_unlock(bridge_channel->chan);
3713         ast_bridge_channel_unlock(bridge_channel);
3714         ao2_ref(old_bridge, -1);
3715 }
3716
3717 /*!
3718  * \internal
3719  * \brief Do the merge of two bridges.
3720  * \since 12.0.0
3721  *
3722  * \param dst_bridge Destination bridge of merge.
3723  * \param src_bridge Source bridge of merge.
3724  * \param kick_me Array of channels to kick from the bridges.
3725  * \param num_kick Number of channels in the kick_me array.
3726  *
3727  * \return Nothing
3728  *
3729  * \note The two bridges are assumed already locked.
3730  *
3731  * This moves the channels in src_bridge into the bridge pointed
3732  * to by dst_bridge.
3733  */
3734 static void bridge_merge_do(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, struct ast_bridge_channel **kick_me, unsigned int num_kick)
3735 {
3736         struct ast_bridge_channel *bridge_channel;
3737         unsigned int idx;
3738
3739         ast_debug(1, "Merging bridge %s into bridge %s\n",
3740                 src_bridge->uniqueid, dst_bridge->uniqueid);
3741
3742         ast_bridge_publish_merge(dst_bridge, src_bridge);
3743
3744         /*
3745          * Move channels from src_bridge over to dst_bridge.
3746          *
3747          * We must use AST_LIST_TRAVERSE_SAFE_BEGIN() because
3748          * bridge_channel_pull() alters the list we are traversing.
3749          */
3750         AST_LIST_TRAVERSE_SAFE_BEGIN(&src_bridge->channels, bridge_channel, entry) {
3751                 if (bridge_channel->state != AST_BRIDGE_CHANNEL_STATE_WAIT) {
3752                         /*
3753                          * The channel is already leaving let it leave normally because
3754                          * pulling it may delete hooks that should run for this channel.
3755                          */
3756                         continue;
3757                 }
3758                 if (ast_test_flag(&bridge_channel->features->feature_flags,
3759                         AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
3760                         continue;
3761                 }
3762
3763                 if (kick_me) {
3764                         for (idx = 0; idx < num_kick; ++idx) {
3765                                 if (bridge_channel == kick_me[idx]) {
3766                                         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
3767                                         break;
3768                                 }
3769                         }
3770                 }
3771                 bridge_channel_pull(bridge_channel);
3772                 if (bridge_channel->state != AST_BRIDGE_CHANNEL_STATE_WAIT) {
3773                         /*
3774                          * The channel died as a result of being pulled or it was
3775                          * kicked.  Leave it pointing to the original bridge.
3776                          */
3777                         continue;
3778                 }
3779
3780                 /* Point to new bridge.*/
3781                 bridge_channel_change_bridge(bridge_channel, dst_bridge);
3782
3783                 if (bridge_channel_push(bridge_channel)) {
3784                         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
3785                 }
3786         }
3787         AST_LIST_TRAVERSE_SAFE_END;
3788
3789         if (kick_me) {
3790                 /*
3791                  * Now we can kick any channels in the dst_bridge without
3792                  * potentially dissolving the bridge.
3793                  */
3794                 for (idx = 0; idx < num_kick; ++idx) {
3795                         bridge_channel = kick_me[idx];
3796                         ast_bridge_channel_lock(bridge_channel);
3797                         if (bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
3798                                 ast_bridge_change_state_nolock(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
3799                                 bridge_channel_pull(bridge_channel);
3800                         }
3801                         ast_bridge_channel_unlock(bridge_channel);
3802                 }
3803         }
3804
3805         bridge_reconfigured(dst_bridge);
3806         bridge_reconfigured(src_bridge);
3807
3808         ast_debug(1, "Merged bridge %s into bridge %s\n",
3809                 src_bridge->uniqueid, dst_bridge->uniqueid);
3810 }
3811
3812 struct merge_direction {
3813         /*! Destination merge bridge. */
3814         struct ast_bridge *dest;
3815         /*! Source merge bridge. */
3816         struct ast_bridge *src;
3817 };
3818
3819 /*!
3820  * \internal
3821  * \brief Determine which bridge should merge into the other.
3822  * \since 12.0.0
3823  *
3824  * \param bridge1 A bridge for merging
3825  * \param bridge2 A bridge for merging
3826  *
3827  * \note The two bridges are assumed already locked.
3828  *
3829  * \return Which bridge merges into which or NULL bridges if cannot merge.
3830  */
3831 static struct merge_direction bridge_merge_determine_direction(struct ast_bridge *bridge1, struct ast_bridge *bridge2)
3832 {
3833         struct merge_direction merge = { NULL, NULL };
3834         int bridge1_priority;
3835         int bridge2_priority;
3836
3837         if (!ast_test_flag(&bridge1->feature_flags,
3838                         AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)
3839                 && !ast_test_flag(&bridge2->feature_flags,
3840                         AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
3841                 /*
3842                  * Can merge either way.  Merge to the higher priority merge
3843                  * bridge.  Otherwise merge to the larger bridge.
3844                  */
3845                 bridge1_priority = bridge1->v_table->get_merge_priority(bridge1);
3846                 bridge2_priority = bridge2->v_table->get_merge_priority(bridge2);
3847                 if (bridge2_priority < bridge1_priority) {
3848                         merge.dest = bridge1;
3849                         merge.src = bridge2;
3850                 } else if (bridge1_priority < bridge2_priority) {
3851                         merge.dest = bridge2;
3852                         merge.src = bridge1;
3853                 } else {
3854                         /* Merge to the larger bridge. */
3855                         if (bridge2->num_channels <= bridge1->num_channels) {
3856                                 merge.dest = bridge1;
3857                                 merge.src = bridge2;
3858                         } else {
3859                                 merge.dest = bridge2;
3860                                 merge.src = bridge1;
3861                         }
3862                 }
3863         } else if (!ast_test_flag(&bridge1->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
3864                 && !ast_test_flag(&bridge2->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
3865                 /* Can merge only one way. */
3866                 merge.dest = bridge1;
3867                 merge.src = bridge2;
3868         } else if (!ast_test_flag(&bridge2->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
3869                 && !ast_test_flag(&bridge1->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
3870                 /* Can merge only one way. */
3871                 merge.dest = bridge2;
3872                 merge.src = bridge1;
3873         }
3874
3875         return merge;
3876 }
3877
3878 /*!
3879  * \internal
3880  * \brief Merge two bridges together
3881  * \since 12.0.0
3882  *
3883  * \param dst_bridge Destination bridge of merge.
3884  * \param src_bridge Source bridge of merge.
3885  * \param merge_best_direction TRUE if don't care about which bridge merges into the other.
3886  * \param kick_me Array of channels to kick from the bridges.
3887  * \param num_kick Number of channels in the kick_me array.
3888  *
3889  * \note The dst_bridge and src_bridge are assumed already locked.
3890  *
3891  * \retval 0 on success
3892  * \retval -1 on failure
3893  */
3894 static int bridge_merge_locked(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, int merge_best_direction, struct ast_channel **kick_me, unsigned int num_kick)
3895 {
3896         struct merge_direction merge;
3897         struct ast_bridge_channel **kick_them = NULL;
3898
3899         /* Sanity check. */
3900         ast_assert(dst_bridge && src_bridge && dst_bridge != src_bridge && (!num_kick || kick_me));
3901
3902         if (dst_bridge->dissolved || src_bridge->dissolved) {
3903                 ast_debug(1, "Can't merge bridges %s and %s, at least one bridge is dissolved.\n",
3904                         src_bridge->uniqueid, dst_bridge->uniqueid);
3905                 return -1;
3906         }
3907         if (ast_test_flag(&dst_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)
3908                 || ast_test_flag(&src_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
3909                 ast_debug(1, "Can't merge bridges %s and %s, masquerade only.\n",
3910                         src_bridge->uniqueid, dst_bridge->uniqueid);
3911                 return -1;
3912         }
3913         if (dst_bridge->inhibit_merge || src_bridge->inhibit_merge) {
3914                 ast_debug(1, "Can't merge bridges %s and %s, merging temporarily inhibited.\n",
3915                         src_bridge->uniqueid, dst_bridge->uniqueid);
3916                 return -1;
3917         }
3918
3919         if (merge_best_direction) {
3920                 merge = bridge_merge_determine_direction(dst_bridge, src_bridge);
3921         } else {
3922                 merge.dest = dst_bridge;
3923                 merge.src = src_bridge;
3924         }
3925
3926         if (!merge.dest
3927                 || ast_test_flag(&merge.dest->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
3928                 || ast_test_flag(&merge.src->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
3929                 ast_debug(1, "Can't merge bridges %s and %s, merging inhibited.\n",
3930                         src_bridge->uniqueid, dst_bridge->uniqueid);
3931                 return -1;
3932         }
3933         if (merge.src->num_channels < 2) {
3934                 /*
3935                  * For a two party bridge, a channel may be temporarily removed
3936                  * from the source bridge or the initial bridge members have not
3937                  * joined yet.
3938                  */
3939                 ast_debug(1, "Can't merge bridge %s into bridge %s, not enough channels in source bridge.\n",
3940                         merge.src->uniqueid, merge.dest->uniqueid);
3941                 return -1;
3942         }
3943    &