4631e5a5276274daa2dd77a344b863a05b7cf0d7
[asterisk/asterisk.git] / main / bridge.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2007 - 2009, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Bridging API
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  */
25
26 /*** MODULEINFO
27         <support_level>core</support_level>
28  ***/
29
30 /*** DOCUMENTATION
31         <manager name="BridgeTechnologyList" language="en_US">
32                 <synopsis>
33                         List available bridging technologies and their statuses.
34                 </synopsis>
35                 <syntax>
36                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
37                 </syntax>
38                 <description>
39                         <para>Returns detailed information about the available bridging technologies.</para>
40                 </description>
41                 <see-also>
42                         <ref type="manager">BridgeTechnologySuspend</ref>
43                         <ref type="manager">BridgeTechnologyUnsuspend</ref>
44                 </see-also>
45         </manager>
46         <manager name="BridgeTechnologySuspend" language="en_US">
47                 <synopsis>
48                         Suspend a bridging technology.
49                 </synopsis>
50                 <syntax>
51                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
52                         <parameter name="BridgeTechnology" required="true">
53                                 <para>The name of the bridging technology to suspend.</para>
54                         </parameter>
55                 </syntax>
56                 <description>
57                         <para>Marks a bridging technology as suspended, which prevents subsequently created bridges from using it.</para>
58                 </description>
59                 <see-also>
60                         <ref type="manager">BridgeTechnologySuspend</ref>
61                         <ref type="manager">BridgeTechnologyUnsuspend</ref>
62                 </see-also>
63         </manager>
64         <manager name="BridgeTechnologyUnsuspend" language="en_US">
65                 <synopsis>
66                         Unsuspend a bridging technology.
67                 </synopsis>
68                 <syntax>
69                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
70                         <parameter name="BridgeTechnology" required="true">
71                                 <para>The name of the bridging technology to unsuspend.</para>
72                         </parameter>
73                 </syntax>
74                 <description>
75                         <para>Clears a previously suspended bridging technology, which allows subsequently created bridges to use it.</para>
76                 </description>
77                 <see-also>
78                         <ref type="manager">BridgeTechnologyList</ref>
79                         <ref type="manager">BridgeTechnologySuspend</ref>
80                 </see-also>
81         </manager>
82 ***/
83
84 #include "asterisk.h"
85
86 #include "asterisk/logger.h"
87 #include "asterisk/channel.h"
88 #include "asterisk/options.h"
89 #include "asterisk/utils.h"
90 #include "asterisk/lock.h"
91 #include "asterisk/linkedlists.h"
92 #include "asterisk/bridge.h"
93 #include "asterisk/bridge_internal.h"
94 #include "asterisk/bridge_channel_internal.h"
95 #include "asterisk/bridge_features.h"
96 #include "asterisk/bridge_basic.h"
97 #include "asterisk/bridge_technology.h"
98 #include "asterisk/bridge_channel.h"
99 #include "asterisk/bridge_after.h"
100 #include "asterisk/stasis_bridges.h"
101 #include "asterisk/stasis_channels.h"
102 #include "asterisk/stasis_cache_pattern.h"
103 #include "asterisk/app.h"
104 #include "asterisk/file.h"
105 #include "asterisk/module.h"
106 #include "asterisk/astobj2.h"
107 #include "asterisk/pbx.h"
108 #include "asterisk/test.h"
109 #include "asterisk/_private.h"
110 #include "asterisk/heap.h"
111 #include "asterisk/say.h"
112 #include "asterisk/timing.h"
113 #include "asterisk/stringfields.h"
114 #include "asterisk/musiconhold.h"
115 #include "asterisk/features.h"
116 #include "asterisk/cli.h"
117 #include "asterisk/parking.h"
118 #include "asterisk/core_local.h"
119 #include "asterisk/core_unreal.h"
120 #include "asterisk/causes.h"
121
122 /*! All bridges container. */
123 static struct ao2_container *bridges;
124
125 static AST_RWLIST_HEAD_STATIC(bridge_technologies, ast_bridge_technology);
126
127 static unsigned int optimization_id;
128
129 /* Initial starting point for the bridge array of channels */
130 #define BRIDGE_ARRAY_START 128
131
132 /* Grow rate of bridge array of channels */
133 #define BRIDGE_ARRAY_GROW 32
134
135 /* Variable name - stores peer information about the most recent blind transfer */
136 #define BLINDTRANSFER "BLINDTRANSFER"
137
138 /* Variable name - stores peer information about the most recent attended transfer */
139 #define ATTENDEDTRANSFER "ATTENDEDTRANSFER"
140
141 static void cleanup_video_mode(struct ast_bridge *bridge);
142
143 /*! Default DTMF keys for built in features */
144 static char builtin_features_dtmf[AST_BRIDGE_BUILTIN_END][MAXIMUM_DTMF_FEATURE_STRING];
145
146 /*! Function handlers for the built in features */
147 static ast_bridge_hook_callback builtin_features_handlers[AST_BRIDGE_BUILTIN_END];
148
149 /*! Function handlers for built in interval features */
150 static ast_bridge_builtin_set_limits_fn builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_END];
151
152 /*! Bridge manager service request */
153 struct bridge_manager_request {
154         /*! List of bridge service requests. */
155         AST_LIST_ENTRY(bridge_manager_request) node;
156         /*! Refed bridge requesting service. */
157         struct ast_bridge *bridge;
158 };
159
160 struct bridge_manager_controller {
161         /*! Condition, used to wake up the bridge manager thread. */
162         ast_cond_t cond;
163         /*! Queue of bridge service requests. */
164         AST_LIST_HEAD_NOLOCK(, bridge_manager_request) service_requests;
165         /*! Manager thread */
166         pthread_t thread;
167         /*! TRUE if the manager needs to stop. */
168         unsigned int stop:1;
169 };
170
171 /*! Bridge manager controller. */
172 static struct bridge_manager_controller *bridge_manager;
173
174 /*!
175  * \internal
176  * \brief Request service for a bridge from the bridge manager.
177  * \since 12.0.0
178  *
179  * \param bridge Requesting service.
180  *
181  * \return Nothing
182  */
183 static void bridge_manager_service_req(struct ast_bridge *bridge)
184 {
185         struct bridge_manager_request *request;
186
187         ao2_lock(bridge_manager);
188         if (bridge_manager->stop) {
189                 ao2_unlock(bridge_manager);
190                 return;
191         }
192
193         /* Create the service request. */
194         request = ast_calloc(1, sizeof(*request));
195         if (!request) {
196                 /* Well. This isn't good. */
197                 ao2_unlock(bridge_manager);
198                 return;
199         }
200         ao2_ref(bridge, +1);
201         request->bridge = bridge;
202
203         /* Put request into the queue and wake the bridge manager. */
204         AST_LIST_INSERT_TAIL(&bridge_manager->service_requests, request, node);
205         ast_cond_signal(&bridge_manager->cond);
206         ao2_unlock(bridge_manager);
207 }
208
209 int __ast_bridge_technology_register(struct ast_bridge_technology *technology, struct ast_module *module)
210 {
211         struct ast_bridge_technology *current;
212
213         /* Perform a sanity check to make sure the bridge technology conforms to our needed requirements */
214         if (ast_strlen_zero(technology->name)
215                 || !technology->capabilities
216                 || !technology->write) {
217                 ast_log(LOG_WARNING, "Bridge technology %s failed registration sanity check.\n",
218                         technology->name);
219                 return -1;
220         }
221
222         AST_RWLIST_WRLOCK(&bridge_technologies);
223
224         /* Look for duplicate bridge technology already using this name, or already registered */
225         AST_RWLIST_TRAVERSE(&bridge_technologies, current, entry) {
226                 if ((!strcasecmp(current->name, technology->name)) || (current == technology)) {
227                         ast_log(LOG_WARNING, "A bridge technology of %s already claims to exist in our world.\n",
228                                 technology->name);
229                         AST_RWLIST_UNLOCK(&bridge_technologies);
230                         return -1;
231                 }
232         }
233
234         /* Copy module pointer so reference counting can keep the module from unloading */
235         technology->mod = module;
236
237         /* Insert our new bridge technology into the list and print out a pretty message */
238         AST_RWLIST_INSERT_TAIL(&bridge_technologies, technology, entry);
239
240         AST_RWLIST_UNLOCK(&bridge_technologies);
241
242         ast_verb(2, "Registered bridge technology %s\n", technology->name);
243
244         return 0;
245 }
246
247 int ast_bridge_technology_unregister(struct ast_bridge_technology *technology)
248 {
249         struct ast_bridge_technology *current;
250
251         AST_RWLIST_WRLOCK(&bridge_technologies);
252
253         /* Ensure the bridge technology is registered before removing it */
254         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&bridge_technologies, current, entry) {
255                 if (current == technology) {
256                         AST_RWLIST_REMOVE_CURRENT(entry);
257                         ast_verb(2, "Unregistered bridge technology %s\n", technology->name);
258                         break;
259                 }
260         }
261         AST_RWLIST_TRAVERSE_SAFE_END;
262
263         AST_RWLIST_UNLOCK(&bridge_technologies);
264
265         return current ? 0 : -1;
266 }
267
268 /*!
269  * \internal
270  * \brief Put an action onto the specified bridge. Don't dup the action frame.
271  * \since 12.0.0
272  *
273  * \param bridge What to queue the action on.
274  * \param action What to do.
275  *
276  * \return Nothing
277  */
278 static void bridge_queue_action_nodup(struct ast_bridge *bridge, struct ast_frame *action)
279 {
280         ast_debug(1, "Bridge %s: queueing action type:%u sub:%d\n",
281                 bridge->uniqueid, action->frametype, action->subclass.integer);
282
283         ast_bridge_lock(bridge);
284         AST_LIST_INSERT_TAIL(&bridge->action_queue, action, frame_list);
285         ast_bridge_unlock(bridge);
286         bridge_manager_service_req(bridge);
287 }
288
289 int ast_bridge_queue_action(struct ast_bridge *bridge, struct ast_frame *action)
290 {
291         struct ast_frame *dup;
292
293         dup = ast_frdup(action);
294         if (!dup) {
295                 return -1;
296         }
297         bridge_queue_action_nodup(bridge, dup);
298         return 0;
299 }
300
301 void bridge_dissolve(struct ast_bridge *bridge, int cause)
302 {
303         struct ast_bridge_channel *bridge_channel;
304         struct ast_frame action = {
305                 .frametype = AST_FRAME_BRIDGE_ACTION,
306                 .subclass.integer = BRIDGE_CHANNEL_ACTION_DEFERRED_DISSOLVING,
307         };
308
309         if (bridge->dissolved) {
310                 return;
311         }
312         bridge->dissolved = 1;
313
314         if (cause <= 0) {
315                 cause = AST_CAUSE_NORMAL_CLEARING;
316         }
317         bridge->cause = cause;
318
319         ast_debug(1, "Bridge %s: dissolving bridge with cause %d(%s)\n",
320                 bridge->uniqueid, cause, ast_cause2str(cause));
321
322         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
323                 ast_bridge_channel_leave_bridge(bridge_channel,
324                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, cause);
325         }
326
327         /* Must defer dissolving bridge because it is already locked. */
328         ast_bridge_queue_action(bridge, &action);
329 }
330
331 /*!
332  * \internal
333  * \brief Check if a bridge should dissolve because of a stolen channel and do it.
334  * \since 12.0.0
335  *
336  * \param bridge Bridge to check.
337  * \param bridge_channel Stolen channel causing the check.  It is not in the bridge to check and may be in another bridge.
338  *
339  * \note On entry, bridge and bridge_channel->bridge are already locked.
340  *
341  * \return Nothing
342  */
343 static void bridge_dissolve_check_stolen(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
344 {
345         if (bridge->dissolved) {
346                 return;
347         }
348
349         if (bridge_channel->features->usable
350                 && ast_test_flag(&bridge_channel->features->feature_flags,
351                         AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP)) {
352                 /* The stolen channel controlled the bridge it was stolen from. */
353                 bridge_dissolve(bridge, 0);
354                 return;
355         }
356         if (bridge->num_channels < 2
357                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)) {
358                 /*
359                  * The stolen channel has not left enough channels to keep the
360                  * bridge alive.  Assume the stolen channel hung up.
361                  */
362                 bridge_dissolve(bridge, 0);
363                 return;
364         }
365 }
366
367 /*!
368  * \internal
369  * \brief Update connected line information after a bridge has been reconfigured.
370  *
371  * \param bridge The bridge itself.
372  *
373  * \return Nothing
374  */
375 static void bridge_reconfigured_connected_line_update(struct ast_bridge *bridge)
376 {
377         struct ast_party_connected_line connected;
378         struct ast_bridge_channel *bridge_channel = AST_LIST_FIRST(&bridge->channels), *peer;
379         unsigned char data[1024];
380         size_t datalen;
381
382         if (!bridge_channel ||
383                 !(bridge->technology->capabilities & (AST_BRIDGE_CAPABILITY_1TO1MIX | AST_BRIDGE_CAPABILITY_NATIVE)) ||
384                 !(peer = ast_bridge_channel_peer(bridge_channel)) ||
385                 ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_ZOMBIE) ||
386                 ast_test_flag(ast_channel_flags(peer->chan), AST_FLAG_ZOMBIE) ||
387                 ast_check_hangup_locked(bridge_channel->chan) ||
388                 ast_check_hangup_locked(peer->chan)) {
389                 return;
390         }
391
392         ast_party_connected_line_init(&connected);
393
394         ast_channel_lock(bridge_channel->chan);
395         ast_connected_line_copy_from_caller(&connected, ast_channel_caller(bridge_channel->chan));
396         ast_channel_unlock(bridge_channel->chan);
397
398         if ((datalen = ast_connected_line_build_data(data, sizeof(data), &connected, NULL)) != (size_t) -1) {
399                 ast_bridge_channel_queue_control_data(peer, AST_CONTROL_CONNECTED_LINE, data, datalen);
400         }
401
402         ast_channel_lock(peer->chan);
403         ast_connected_line_copy_from_caller(&connected, ast_channel_caller(peer->chan));
404         ast_channel_unlock(peer->chan);
405
406         if ((datalen = ast_connected_line_build_data(data, sizeof(data), &connected, NULL)) != (size_t) -1) {
407                 ast_bridge_channel_queue_control_data(bridge_channel, AST_CONTROL_CONNECTED_LINE, data, datalen);
408         }
409
410         ast_party_connected_line_free(&connected);
411 }
412
413 /*!
414  * \internal
415  * \brief Complete joining a channel to the bridge.
416  * \since 12.0.0
417  *
418  * \param bridge What to operate upon.
419  * \param bridge_channel What is joining the bridge technology.
420  *
421  * \note On entry, bridge is already locked.
422  *
423  * \return Nothing
424  */
425 static void bridge_channel_complete_join(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
426 {
427         /* Tell the bridge technology we are joining so they set us up */
428         ast_debug(1, "Bridge %s: %p(%s) is joining %s technology\n",
429                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
430                 bridge->technology->name);
431         if (bridge->technology->join
432                 && bridge->technology->join(bridge, bridge_channel)) {
433                 /* We cannot leave the channel partially in the bridge so we must kick it out */
434                 ast_debug(1, "Bridge %s: %p(%s) failed to join %s technology (Kicking it out)\n",
435                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
436                         bridge->technology->name);
437                 bridge_channel->just_joined = 1;
438                 ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END, 0);
439                 return;
440         }
441
442         bridge_channel->just_joined = 0;
443
444         /*
445          * When a channel joins the bridge its streams need to be mapped to the bridge's
446          * media types vector. This way all streams map to the same media type index for
447          * a given channel.
448          */
449         ast_bridge_channel_stream_map(bridge_channel);
450 }
451
452 /*!
453  * \internal
454  * \brief Complete joining new channels to the bridge.
455  * \since 12.0.0
456  *
457  * \param bridge Check for new channels on this bridge.
458  *
459  * \note On entry, bridge is already locked.
460  *
461  * \return Nothing
462  */
463 static void bridge_complete_join(struct ast_bridge *bridge)
464 {
465         struct ast_bridge_channel *bridge_channel;
466
467         if (bridge->dissolved) {
468                 /*
469                  * No sense in completing the join on channels for a dissolved
470                  * bridge.  They are just going to be removed soon anyway.
471                  * However, we do have reason to abort here because the bridge
472                  * technology may not be able to handle the number of channels
473                  * still in the bridge.
474                  */
475                 return;
476         }
477
478         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
479                 if (!bridge_channel->just_joined) {
480                         continue;
481                 }
482                 bridge_channel_complete_join(bridge, bridge_channel);
483         }
484 }
485
486 /*! \brief Helper function used to find the "best" bridge technology given specified capabilities */
487 static struct ast_bridge_technology *find_best_technology(uint32_t capabilities, struct ast_bridge *bridge)
488 {
489         struct ast_bridge_technology *current;
490         struct ast_bridge_technology *best = NULL;
491
492         AST_RWLIST_RDLOCK(&bridge_technologies);
493         AST_RWLIST_TRAVERSE(&bridge_technologies, current, entry) {
494                 if (current->suspended) {
495                         ast_debug(1, "Bridge technology %s is suspended. Skipping.\n",
496                                 current->name);
497                         continue;
498                 }
499                 if (!(current->capabilities & capabilities)) {
500                         ast_debug(1, "Bridge technology %s does not have any capabilities we want.\n",
501                                 current->name);
502                         continue;
503                 }
504                 if (best && current->preference <= best->preference) {
505                         ast_debug(1, "Bridge technology %s has less preference than %s (%u <= %u). Skipping.\n",
506                                 current->name, best->name, current->preference, best->preference);
507                         continue;
508                 }
509                 if (current->compatible && !current->compatible(bridge)) {
510                         ast_debug(1, "Bridge technology %s is not compatible with properties of existing bridge.\n",
511                                 current->name);
512                         continue;
513                 }
514                 best = current;
515         }
516
517         if (best) {
518                 /* Increment it's module reference count if present so it does not get unloaded while in use */
519                 ast_module_ref(best->mod);
520                 ast_debug(1, "Chose bridge technology %s\n", best->name);
521         }
522
523         AST_RWLIST_UNLOCK(&bridge_technologies);
524
525         return best;
526 }
527
528 struct tech_deferred_destroy {
529         struct ast_bridge_technology *tech;
530         void *tech_pvt;
531 };
532
533 /*!
534  * \internal
535  * \brief Deferred destruction of bridge tech private structure.
536  * \since 12.0.0
537  *
538  * \param bridge What to execute the action on.
539  * \param action Deferred bridge tech destruction.
540  *
541  * \note On entry, bridge must not be locked.
542  *
543  * \return Nothing
544  */
545 static void bridge_tech_deferred_destroy(struct ast_bridge *bridge, struct ast_frame *action)
546 {
547         struct tech_deferred_destroy *deferred = action->data.ptr;
548         struct ast_bridge dummy_bridge = {
549                 .technology = deferred->tech,
550                 .tech_pvt = deferred->tech_pvt,
551                 .creator = bridge->creator,
552                 .name = bridge->name,
553                 .uniqueid = bridge->uniqueid,
554                 };
555
556         ast_debug(1, "Bridge %s: calling %s technology destructor (deferred, dummy)\n",
557                 dummy_bridge.uniqueid, dummy_bridge.technology->name);
558         dummy_bridge.technology->destroy(&dummy_bridge);
559         ast_module_unref(dummy_bridge.technology->mod);
560 }
561
562 /*!
563  * \internal
564  * \brief Handle bridge action frame.
565  * \since 12.0.0
566  *
567  * \param bridge What to execute the action on.
568  * \param action What to do.
569  *
570  * \note On entry, bridge is already locked.
571  * \note Can be called by the bridge destructor.
572  *
573  * \return Nothing
574  */
575 static void bridge_action_bridge(struct ast_bridge *bridge, struct ast_frame *action)
576 {
577 #if 0   /* In case we need to know when the destructor is calling us. */
578         int in_destructor = !ao2_ref(bridge, 0);
579 #endif
580
581         switch (action->subclass.integer) {
582         case BRIDGE_CHANNEL_ACTION_DEFERRED_TECH_DESTROY:
583                 ast_bridge_unlock(bridge);
584                 bridge_tech_deferred_destroy(bridge, action);
585                 ast_bridge_lock(bridge);
586                 break;
587         case BRIDGE_CHANNEL_ACTION_DEFERRED_DISSOLVING:
588                 ast_bridge_unlock(bridge);
589                 bridge->v_table->dissolving(bridge);
590                 ast_bridge_lock(bridge);
591                 break;
592         default:
593                 /* Unexpected deferred action type.  Should never happen. */
594                 ast_assert(0);
595                 break;
596         }
597 }
598
599 /*!
600  * \internal
601  * \brief Do any pending bridge actions.
602  * \since 12.0.0
603  *
604  * \param bridge What to do actions on.
605  *
606  * \note On entry, bridge is already locked.
607  * \note Can be called by the bridge destructor.
608  *
609  * \return Nothing
610  */
611 static void bridge_handle_actions(struct ast_bridge *bridge)
612 {
613         struct ast_frame *action;
614
615         while ((action = AST_LIST_REMOVE_HEAD(&bridge->action_queue, frame_list))) {
616                 switch (action->frametype) {
617                 case AST_FRAME_BRIDGE_ACTION:
618                         bridge_action_bridge(bridge, action);
619                         break;
620                 default:
621                         /* Unexpected deferred frame type.  Should never happen. */
622                         ast_assert(0);
623                         break;
624                 }
625                 ast_frfree(action);
626         }
627 }
628
629 static struct stasis_message *create_bridge_snapshot_message(struct ast_bridge *bridge)
630 {
631         RAII_VAR(struct ast_bridge_snapshot *, snapshot, NULL, ao2_cleanup);
632
633         if (!ast_bridge_snapshot_type()) {
634                 return NULL;
635         }
636
637         ast_bridge_lock(bridge);
638         snapshot = ast_bridge_snapshot_create(bridge);
639         ast_bridge_unlock(bridge);
640
641         if (!snapshot) {
642                 return NULL;
643         }
644
645         return stasis_message_create(ast_bridge_snapshot_type(), snapshot);
646 }
647
648 static void destroy_bridge(void *obj)
649 {
650         struct ast_bridge *bridge = obj;
651
652         ast_debug(1, "Bridge %s: actually destroying %s bridge, nobody wants it anymore\n",
653                 bridge->uniqueid, bridge->v_table->name);
654
655         if (bridge->construction_completed) {
656                 RAII_VAR(struct stasis_message *, clear_msg, NULL, ao2_cleanup);
657
658                 clear_msg = create_bridge_snapshot_message(bridge);
659                 if (clear_msg) {
660                         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
661
662                         msg = stasis_cache_clear_create(clear_msg);
663                         if (msg) {
664                                 stasis_publish(ast_bridge_topic(bridge), msg);
665                         }
666                 }
667         }
668
669         /* Do any pending actions in the context of destruction. */
670         ast_bridge_lock(bridge);
671         bridge_handle_actions(bridge);
672         ast_bridge_unlock(bridge);
673
674         /* There should not be any channels left in the bridge. */
675         ast_assert(AST_LIST_EMPTY(&bridge->channels));
676
677         ast_debug(1, "Bridge %s: calling %s bridge destructor\n",
678                 bridge->uniqueid, bridge->v_table->name);
679         bridge->v_table->destroy(bridge);
680
681         /* Pass off the bridge to the technology to destroy if needed */
682         if (bridge->technology) {
683                 ast_debug(1, "Bridge %s: calling %s technology stop\n",
684                         bridge->uniqueid, bridge->technology->name);
685                 if (bridge->technology->stop) {
686                         ast_bridge_lock(bridge);
687                         bridge->technology->stop(bridge);
688                         ast_bridge_unlock(bridge);
689                 }
690                 ast_debug(1, "Bridge %s: calling %s technology destructor\n",
691                         bridge->uniqueid, bridge->technology->name);
692                 if (bridge->technology->destroy) {
693                         bridge->technology->destroy(bridge);
694                 }
695                 ast_module_unref(bridge->technology->mod);
696                 bridge->technology = NULL;
697         }
698
699         AST_VECTOR_FREE(&bridge->media_types);
700
701         bridge->callid = 0;
702
703         cleanup_video_mode(bridge);
704
705         stasis_cp_single_unsubscribe(bridge->topics);
706
707         ast_string_field_free_memory(bridge);
708 }
709
710 struct ast_bridge *bridge_register(struct ast_bridge *bridge)
711 {
712         if (bridge) {
713                 bridge->construction_completed = 1;
714                 ast_bridge_lock(bridge);
715                 ast_bridge_publish_state(bridge);
716                 ast_bridge_unlock(bridge);
717                 if (!ao2_link(bridges, bridge)) {
718                         ast_bridge_destroy(bridge, 0);
719                         bridge = NULL;
720                 }
721         }
722         return bridge;
723 }
724
725 struct ast_bridge *bridge_alloc(size_t size, const struct ast_bridge_methods *v_table)
726 {
727         struct ast_bridge *bridge;
728
729         /* Check v_table that all methods are present. */
730         if (!v_table
731                 || !v_table->name
732                 || !v_table->destroy
733                 || !v_table->dissolving
734                 || !v_table->push
735                 || !v_table->pull
736                 || !v_table->notify_masquerade
737                 || !v_table->get_merge_priority) {
738                 ast_log(LOG_ERROR, "Virtual method table for bridge class %s not complete.\n",
739                         v_table && v_table->name ? v_table->name : "<unknown>");
740                 ast_assert(0);
741                 return NULL;
742         }
743
744         bridge = ao2_alloc(size, destroy_bridge);
745         if (!bridge) {
746                 return NULL;
747         }
748
749         if (ast_string_field_init(bridge, 80)) {
750                 ao2_cleanup(bridge);
751                 return NULL;
752         }
753
754         bridge->v_table = v_table;
755
756         AST_VECTOR_INIT(&bridge->media_types, AST_MEDIA_TYPE_END);
757
758         return bridge;
759 }
760
761 struct ast_bridge *bridge_base_init(struct ast_bridge *self, uint32_t capabilities, unsigned int flags, const char *creator, const char *name, const char *id)
762 {
763         char uuid_hold[AST_UUID_STR_LEN];
764
765         if (!self) {
766                 return NULL;
767         }
768
769         if (!ast_strlen_zero(id)) {
770                 ast_string_field_set(self, uniqueid, id);
771         } else {
772                 ast_uuid_generate_str(uuid_hold, AST_UUID_STR_LEN);
773                 ast_string_field_set(self, uniqueid, uuid_hold);
774         }
775         ast_string_field_set(self, creator, creator);
776         if (!ast_strlen_zero(creator)) {
777                 ast_string_field_set(self, name, name);
778         }
779
780         ast_set_flag(&self->feature_flags, flags);
781         self->allowed_capabilities = capabilities;
782
783         if (!(flags & AST_BRIDGE_FLAG_INVISIBLE)) {
784                 if (bridge_topics_init(self) != 0) {
785                         ast_log(LOG_WARNING, "Bridge %s: Could not initialize topics\n",
786                                 self->uniqueid);
787                         ao2_ref(self, -1);
788                         return NULL;
789                 }
790         }
791
792         /* Use our helper function to find the "best" bridge technology. */
793         self->technology = find_best_technology(capabilities, self);
794         if (!self->technology) {
795                 ast_log(LOG_WARNING, "Bridge %s: Could not create class %s.  No technology to support it.\n",
796                         self->uniqueid, self->v_table->name);
797                 ao2_ref(self, -1);
798                 return NULL;
799         }
800
801         /* Pass off the bridge to the technology to manipulate if needed */
802         ast_debug(1, "Bridge %s: calling %s technology constructor\n",
803                 self->uniqueid, self->technology->name);
804         if (self->technology->create && self->technology->create(self)) {
805                 ast_log(LOG_WARNING, "Bridge %s: failed to setup bridge technology %s\n",
806                         self->uniqueid, self->technology->name);
807                 ao2_ref(self, -1);
808                 return NULL;
809         }
810         ast_debug(1, "Bridge %s: calling %s technology start\n",
811                 self->uniqueid, self->technology->name);
812         if (self->technology->start && self->technology->start(self)) {
813                 ast_log(LOG_WARNING, "Bridge %s: failed to start bridge technology %s\n",
814                         self->uniqueid, self->technology->name);
815                 ao2_ref(self, -1);
816                 return NULL;
817         }
818
819         if (!(flags & AST_BRIDGE_FLAG_INVISIBLE)) {
820                 if (!ast_bridge_topic(self)) {
821                         ao2_ref(self, -1);
822                         return NULL;
823                 }
824         }
825
826         return self;
827 }
828
829 /*!
830  * \internal
831  * \brief ast_bridge base class destructor.
832  * \since 12.0.0
833  *
834  * \param self Bridge to operate upon.
835  *
836  * \note Stub because of nothing to do.
837  *
838  * \return Nothing
839  */
840 static void bridge_base_destroy(struct ast_bridge *self)
841 {
842 }
843
844 /*!
845  * \internal
846  * \brief The bridge is being dissolved.
847  * \since 12.0.0
848  *
849  * \param self Bridge to operate upon.
850  *
851  * \return Nothing
852  */
853 static void bridge_base_dissolving(struct ast_bridge *self)
854 {
855         ao2_unlink(bridges, self);
856 }
857
858 /*!
859  * \internal
860  * \brief ast_bridge base push method.
861  * \since 12.0.0
862  *
863  * \param self Bridge to operate upon.
864  * \param bridge_channel Bridge channel to push.
865  * \param swap Bridge channel to swap places with if not NULL.
866  *
867  * \note On entry, self is already locked.
868  * \note Stub because of nothing to do.
869  *
870  * \retval 0 on success
871  * \retval -1 on failure
872  */
873 static int bridge_base_push(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
874 {
875         return 0;
876 }
877
878 /*!
879  * \internal
880  * \brief ast_bridge base pull method.
881  * \since 12.0.0
882  *
883  * \param self Bridge to operate upon.
884  * \param bridge_channel Bridge channel to pull.
885  *
886  * \note On entry, self is already locked.
887  *
888  * \return Nothing
889  */
890 static void bridge_base_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
891 {
892         ast_bridge_features_remove(bridge_channel->features, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
893 }
894
895 /*!
896  * \internal
897  * \brief ast_bridge base notify_masquerade method.
898  * \since 12.0.0
899  *
900  * \param self Bridge to operate upon.
901  * \param bridge_channel Bridge channel that was masqueraded.
902  *
903  * \note On entry, self is already locked.
904  *
905  * \return Nothing
906  */
907 static void bridge_base_notify_masquerade(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
908 {
909         self->reconfigured = 1;
910 }
911
912 /*!
913  * \internal
914  * \brief Get the merge priority of this bridge.
915  * \since 12.0.0
916  *
917  * \param self Bridge to operate upon.
918  *
919  * \note On entry, self is already locked.
920  *
921  * \return Merge priority
922  */
923 static int bridge_base_get_merge_priority(struct ast_bridge *self)
924 {
925         return 0;
926 }
927
928 /*!
929  * \internal
930  * \brief ast_bridge base push_peek method.
931  * \since 13.2.0
932  *
933  * \param self Bridge to operate upon.
934  * \param bridge_channel Bridge channel to push.
935  * \param swap Bridge channel to swap places with if not NULL.
936  *
937  * \note On entry, self is already locked.
938  * \note Stub because of nothing to do.
939  *
940  * \retval 0 on success
941  * \retval -1 on failure
942  */
943 static int bridge_base_push_peek(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
944 {
945         return 0;
946 }
947
948 struct ast_bridge_methods ast_bridge_base_v_table = {
949         .name = "base",
950         .destroy = bridge_base_destroy,
951         .dissolving = bridge_base_dissolving,
952         .push = bridge_base_push,
953         .pull = bridge_base_pull,
954         .notify_masquerade = bridge_base_notify_masquerade,
955         .get_merge_priority = bridge_base_get_merge_priority,
956         .push_peek = bridge_base_push_peek,
957 };
958
959 struct ast_bridge *ast_bridge_base_new(uint32_t capabilities, unsigned int flags, const char *creator, const char *name, const char *id)
960 {
961         void *bridge;
962
963         bridge = bridge_alloc(sizeof(struct ast_bridge), &ast_bridge_base_v_table);
964         bridge = bridge_base_init(bridge, capabilities, flags, creator, name, id);
965         bridge = bridge_register(bridge);
966         return bridge;
967 }
968
969 int ast_bridge_destroy(struct ast_bridge *bridge, int cause)
970 {
971         ast_debug(1, "Bridge %s: telling all channels to leave the party\n", bridge->uniqueid);
972         ast_bridge_lock(bridge);
973         bridge_dissolve(bridge, cause);
974         ast_bridge_unlock(bridge);
975
976         ao2_ref(bridge, -1);
977
978         return 0;
979 }
980
981 /*!
982  * \internal
983  * \brief Perform the smart bridge operation.
984  * \since 12.0.0
985  *
986  * \param bridge Work on this bridge.
987  *
988  * \details
989  * Basically see if a new bridge technology should be used instead
990  * of the current one.
991  *
992  * \note On entry, bridge is already locked.
993  *
994  * \retval 0 on success.
995  * \retval -1 on error.
996  */
997 static int smart_bridge_operation(struct ast_bridge *bridge)
998 {
999         uint32_t new_capabilities;
1000         struct ast_bridge_technology *new_technology;
1001         struct ast_bridge_technology *old_technology = bridge->technology;
1002         struct ast_bridge_channel *bridge_channel;
1003         struct ast_frame *deferred_action;
1004         struct ast_bridge dummy_bridge = {
1005                 .technology = bridge->technology,
1006                 .tech_pvt = bridge->tech_pvt,
1007                 .creator = bridge->creator,
1008                 .name = bridge->name,
1009                 .uniqueid = bridge->uniqueid,
1010         };
1011
1012         if (bridge->dissolved) {
1013                 ast_debug(1, "Bridge %s is dissolved, not performing smart bridge operation.\n",
1014                         bridge->uniqueid);
1015                 return 0;
1016         }
1017
1018         /* Determine new bridge technology capabilities needed. */
1019         if (2 < bridge->num_channels) {
1020                 new_capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX;
1021                 new_capabilities &= bridge->allowed_capabilities;
1022         } else {
1023                 new_capabilities = AST_BRIDGE_CAPABILITY_NATIVE | AST_BRIDGE_CAPABILITY_1TO1MIX;
1024                 new_capabilities &= bridge->allowed_capabilities;
1025                 if (!new_capabilities
1026                         && (bridge->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
1027                         /* Allow switching between different multimix bridge technologies. */
1028                         new_capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX;
1029                 }
1030         }
1031
1032         /* Find a bridge technology to satisfy the new capabilities. */
1033         new_technology = find_best_technology(new_capabilities, bridge);
1034         if (!new_technology) {
1035                 int is_compatible = 0;
1036
1037                 if (old_technology->compatible) {
1038                         is_compatible = old_technology->compatible(bridge);
1039                 } else if (old_technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX) {
1040                         is_compatible = 1;
1041                 } else if (bridge->num_channels <= 2
1042                         && (old_technology->capabilities & AST_BRIDGE_CAPABILITY_1TO1MIX)) {
1043                         is_compatible = 1;
1044                 }
1045
1046                 if (is_compatible) {
1047                         ast_debug(1, "Bridge %s could not get a new technology, staying with old technology.\n",
1048                                 bridge->uniqueid);
1049                         return 0;
1050                 }
1051                 ast_log(LOG_WARNING, "Bridge %s has no technology available to support it.\n",
1052                         bridge->uniqueid);
1053                 return -1;
1054         }
1055         if (new_technology == old_technology) {
1056                 ast_debug(1, "Bridge %s is already using the new technology.\n",
1057                         bridge->uniqueid);
1058                 ast_module_unref(old_technology->mod);
1059                 return 0;
1060         }
1061
1062         if (old_technology->destroy) {
1063                 struct tech_deferred_destroy deferred_tech_destroy = {
1064                         .tech = dummy_bridge.technology,
1065                         .tech_pvt = dummy_bridge.tech_pvt,
1066                 };
1067                 struct ast_frame action = {
1068                         .frametype = AST_FRAME_BRIDGE_ACTION,
1069                         .subclass.integer = BRIDGE_CHANNEL_ACTION_DEFERRED_TECH_DESTROY,
1070                         .data.ptr = &deferred_tech_destroy,
1071                         .datalen = sizeof(deferred_tech_destroy),
1072                 };
1073
1074                 /*
1075                  * We need to defer the bridge technology destroy callback
1076                  * because we have the bridge locked.
1077                  */
1078                 deferred_action = ast_frdup(&action);
1079                 if (!deferred_action) {
1080                         ast_module_unref(new_technology->mod);
1081                         return -1;
1082                 }
1083         } else {
1084                 deferred_action = NULL;
1085         }
1086
1087         /*
1088          * We are now committed to changing the bridge technology.  We
1089          * must not release the bridge lock until we have installed the
1090          * new bridge technology.
1091          */
1092         ast_verb(4, "Bridge %s: switching from %s technology to %s\n",
1093                 bridge->uniqueid, old_technology->name, new_technology->name);
1094
1095         /*
1096          * Since we are soon going to pass this bridge to a new
1097          * technology we need to NULL out the tech_pvt pointer but
1098          * don't worry as it still exists in dummy_bridge, ditto for the
1099          * old technology.
1100          */
1101         bridge->tech_pvt = NULL;
1102         bridge->technology = new_technology;
1103
1104         /* Setup the new bridge technology. */
1105         ast_debug(1, "Bridge %s: calling %s technology constructor\n",
1106                 bridge->uniqueid, new_technology->name);
1107         if (new_technology->create && new_technology->create(bridge)) {
1108                 ast_log(LOG_WARNING, "Bridge %s: failed to setup bridge technology %s\n",
1109                         bridge->uniqueid, new_technology->name);
1110                 bridge->tech_pvt = dummy_bridge.tech_pvt;
1111                 bridge->technology = dummy_bridge.technology;
1112                 ast_module_unref(new_technology->mod);
1113                 return -1;
1114         }
1115
1116         /* To ensure that things are sane for the old technology move the channels it
1117          * expects to the dummy bridge
1118          */
1119         AST_LIST_TRAVERSE_SAFE_BEGIN(&bridge->channels, bridge_channel, entry) {
1120                 if (bridge_channel->just_joined) {
1121                         continue;
1122                 }
1123                 ast_debug(1, "Bridge %s: moving %p(%s) to dummy bridge temporarily\n",
1124                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1125                 AST_LIST_REMOVE_CURRENT(entry);
1126                 AST_LIST_INSERT_TAIL(&dummy_bridge.channels, bridge_channel, entry);
1127                 dummy_bridge.num_channels++;
1128                 if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1129                         dummy_bridge.num_lonely++;
1130                 }
1131                 if (!bridge_channel->suspended) {
1132                         dummy_bridge.num_active++;
1133                 }
1134         }
1135         AST_LIST_TRAVERSE_SAFE_END;
1136
1137         /* Take all the channels out of the old technology */
1138         AST_LIST_TRAVERSE_SAFE_BEGIN(&dummy_bridge.channels, bridge_channel, entry) {
1139                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology (dummy)\n",
1140                         dummy_bridge.uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1141                         old_technology->name);
1142                 if (old_technology->leave) {
1143                         old_technology->leave(&dummy_bridge, bridge_channel);
1144                 }
1145                 AST_LIST_REMOVE_CURRENT(entry);
1146                 AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
1147                 dummy_bridge.num_channels--;
1148                 if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1149                         dummy_bridge.num_lonely--;
1150                 }
1151                 if (!bridge_channel->suspended) {
1152                         dummy_bridge.num_active--;
1153                 }
1154         }
1155         AST_LIST_TRAVERSE_SAFE_END;
1156
1157         ast_debug(1, "Bridge %s: calling %s technology stop\n",
1158                 dummy_bridge.uniqueid, old_technology->name);
1159         if (old_technology->stop) {
1160                 old_technology->stop(&dummy_bridge);
1161         }
1162
1163         /* Add any new channels or re-add existing channels to the bridge. */
1164         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1165                 bridge_channel_complete_join(bridge, bridge_channel);
1166         }
1167
1168         ast_debug(1, "Bridge %s: calling %s technology start\n",
1169                 bridge->uniqueid, new_technology->name);
1170         if (new_technology->start && new_technology->start(bridge)) {
1171                 ast_log(LOG_WARNING, "Bridge %s: failed to start bridge technology %s\n",
1172                         bridge->uniqueid, new_technology->name);
1173         }
1174
1175         /*
1176          * Now that all the channels have been moved over we need to get
1177          * rid of all the information the old technology may have left
1178          * around.
1179          */
1180         if (old_technology->destroy) {
1181                 ast_debug(1, "Bridge %s: deferring %s technology destructor\n",
1182                         dummy_bridge.uniqueid, old_technology->name);
1183                 bridge_queue_action_nodup(bridge, deferred_action);
1184         } else {
1185                 ast_debug(1, "Bridge %s: calling %s technology destructor\n",
1186                         dummy_bridge.uniqueid, old_technology->name);
1187                 ast_module_unref(old_technology->mod);
1188         }
1189
1190         return 0;
1191 }
1192
1193 /*!
1194  * \internal
1195  * \brief Bridge channel to check if a BRIDGE_PLAY_SOUND needs to be played.
1196  * \since 12.0.0
1197  *
1198  * \param bridge_channel What to check.
1199  *
1200  * \return Nothing
1201  */
1202 static void check_bridge_play_sound(struct ast_bridge_channel *bridge_channel)
1203 {
1204         const char *play_file;
1205
1206         ast_channel_lock(bridge_channel->chan);
1207         play_file = pbx_builtin_getvar_helper(bridge_channel->chan, "BRIDGE_PLAY_SOUND");
1208         if (!ast_strlen_zero(play_file)) {
1209                 play_file = ast_strdupa(play_file);
1210                 pbx_builtin_setvar_helper(bridge_channel->chan, "BRIDGE_PLAY_SOUND", NULL);
1211         } else {
1212                 play_file = NULL;
1213         }
1214         ast_channel_unlock(bridge_channel->chan);
1215
1216         if (play_file) {
1217                 ast_bridge_channel_queue_playfile(bridge_channel, NULL, play_file, NULL);
1218         }
1219 }
1220
1221 /*!
1222  * \internal
1223  * \brief Check for any BRIDGE_PLAY_SOUND channel variables in the bridge.
1224  * \since 12.0.0
1225  *
1226  * \param bridge What to operate on.
1227  *
1228  * \note On entry, the bridge is already locked.
1229  *
1230  * \return Nothing
1231  */
1232 static void check_bridge_play_sounds(struct ast_bridge *bridge)
1233 {
1234         struct ast_bridge_channel *bridge_channel;
1235
1236         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1237                 check_bridge_play_sound(bridge_channel);
1238         }
1239 }
1240
1241 void ast_bridge_vars_set(struct ast_channel *chan, const char *name, const char *pvtid)
1242 {
1243         ast_channel_stage_snapshot(chan);
1244         pbx_builtin_setvar_helper(chan, "BRIDGEPEER", name);
1245         pbx_builtin_setvar_helper(chan, "BRIDGEPVTCALLID", pvtid);
1246         ast_channel_stage_snapshot_done(chan);
1247 }
1248
1249 /*!
1250  * \internal
1251  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a 2 party bridge.
1252  * \since 12.0.0
1253  *
1254  * \param c0 Party of the first part.
1255  * \param c1 Party of the second part.
1256  *
1257  * \note On entry, the bridge is already locked.
1258  * \note The bridge is expected to have exactly two parties.
1259  *
1260  * \return Nothing
1261  */
1262 static void set_bridge_peer_vars_2party(struct ast_channel *c0, struct ast_channel *c1)
1263 {
1264         const char *c0_name;
1265         const char *c1_name;
1266         const char *c0_pvtid = NULL;
1267         const char *c1_pvtid = NULL;
1268 #define UPDATE_BRIDGE_VARS_GET(chan, name, pvtid)                                                                       \
1269         do {                                                                                                                                                    \
1270                 name = ast_strdupa(ast_channel_name(chan));                                                                     \
1271                 if (ast_channel_tech(chan)->get_pvt_uniqueid) {                                                         \
1272                         pvtid = ast_strdupa(ast_channel_tech(chan)->get_pvt_uniqueid(chan));    \
1273                 }                                                                                                                                                       \
1274         } while (0)
1275
1276         ast_channel_lock(c1);
1277         UPDATE_BRIDGE_VARS_GET(c1, c1_name, c1_pvtid);
1278         ast_channel_unlock(c1);
1279
1280         ast_channel_lock(c0);
1281         ast_bridge_vars_set(c0, c1_name, c1_pvtid);
1282         UPDATE_BRIDGE_VARS_GET(c0, c0_name, c0_pvtid);
1283         ast_channel_unlock(c0);
1284
1285         ast_channel_lock(c1);
1286         ast_bridge_vars_set(c1, c0_name, c0_pvtid);
1287         ast_channel_unlock(c1);
1288 }
1289
1290 /*!
1291  * \internal
1292  * \brief Fill the BRIDGEPEER value buffer with a comma separated list of channel names.
1293  * \since 12.0.0
1294  *
1295  * \param buf Buffer to fill.  The caller must guarantee the buffer is large enough.
1296  * \param cur_idx Which index into names[] to skip.
1297  * \param names Channel names to put in the buffer.
1298  * \param num_names Number of names in the array.
1299  *
1300  * \return Nothing
1301  */
1302 static void fill_bridgepeer_buf(char *buf, unsigned int cur_idx, const char *names[], unsigned int num_names)
1303 {
1304         int need_separator = 0;
1305         unsigned int idx;
1306         const char *src;
1307         char *pos;
1308
1309         pos = buf;
1310         for (idx = 0; idx < num_names; ++idx) {
1311                 if (idx == cur_idx) {
1312                         continue;
1313                 }
1314
1315                 if (need_separator) {
1316                         *pos++ = ',';
1317                 }
1318                 need_separator = 1;
1319
1320                 /* Copy name into buffer. */
1321                 src = names[idx];
1322                 while (*src) {
1323                         *pos++ = *src++;
1324                 }
1325         }
1326         *pos = '\0';
1327 }
1328
1329 /*!
1330  * \internal
1331  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a multi-party bridge.
1332  * \since 12.0.0
1333  *
1334  * \param bridge What to operate on.
1335  *
1336  * \note On entry, the bridge is already locked.
1337  * \note The bridge is expected to have more than two parties.
1338  *
1339  * \return Nothing
1340  */
1341 static void set_bridge_peer_vars_multiparty(struct ast_bridge *bridge)
1342 {
1343 /*
1344  * Set a maximum number of channel names for the BRIDGEPEER
1345  * list.  The plus one is for the current channel which is not
1346  * put in the list.
1347  */
1348 #define MAX_BRIDGEPEER_CHANS    (10 + 1)
1349
1350         unsigned int idx;
1351         unsigned int num_names;
1352         unsigned int len;
1353         const char **names;
1354         char *buf;
1355         struct ast_bridge_channel *bridge_channel;
1356
1357         /* Get first MAX_BRIDGEPEER_CHANS channel names. */
1358         num_names = MIN(bridge->num_channels, MAX_BRIDGEPEER_CHANS);
1359         names = ast_alloca(num_names * sizeof(*names));
1360         idx = 0;
1361         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1362                 if (num_names <= idx) {
1363                         break;
1364                 }
1365                 ast_channel_lock(bridge_channel->chan);
1366                 names[idx++] = ast_strdupa(ast_channel_name(bridge_channel->chan));
1367                 ast_channel_unlock(bridge_channel->chan);
1368         }
1369
1370         /* Determine maximum buf size needed. */
1371         len = num_names;
1372         for (idx = 0; idx < num_names; ++idx) {
1373                 len += strlen(names[idx]);
1374         }
1375         buf = ast_alloca(len);
1376
1377         /* Set the bridge channel variables. */
1378         idx = 0;
1379         buf[0] = '\0';
1380         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1381                 if (idx < num_names) {
1382                         fill_bridgepeer_buf(buf, idx, names, num_names);
1383                 }
1384                 ++idx;
1385
1386                 ast_channel_lock(bridge_channel->chan);
1387                 ast_bridge_vars_set(bridge_channel->chan, buf, NULL);
1388                 ast_channel_unlock(bridge_channel->chan);
1389         }
1390 }
1391
1392 /*!
1393  * \internal
1394  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a holding bridge.
1395  * \since 12.0.0
1396  *
1397  * \param bridge What to operate on.
1398  *
1399  * \note On entry, the bridge is already locked.
1400  *
1401  * \return Nothing
1402  */
1403 static void set_bridge_peer_vars_holding(struct ast_bridge *bridge)
1404 {
1405         struct ast_bridge_channel *bridge_channel;
1406
1407         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1408                 ast_channel_lock(bridge_channel->chan);
1409                 ast_bridge_vars_set(bridge_channel->chan, NULL, NULL);
1410                 ast_channel_unlock(bridge_channel->chan);
1411         }
1412 }
1413
1414 /*!
1415  * \internal
1416  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in the bridge.
1417  * \since 12.0.0
1418  *
1419  * \param bridge What to operate on.
1420  *
1421  * \note On entry, the bridge is already locked.
1422  *
1423  * \return Nothing
1424  */
1425 static void set_bridge_peer_vars(struct ast_bridge *bridge)
1426 {
1427         if (bridge->technology->capabilities & AST_BRIDGE_CAPABILITY_HOLDING) {
1428                 set_bridge_peer_vars_holding(bridge);
1429                 return;
1430         }
1431         if (bridge->num_channels < 2) {
1432                 return;
1433         }
1434         if (bridge->num_channels == 2) {
1435                 set_bridge_peer_vars_2party(AST_LIST_FIRST(&bridge->channels)->chan,
1436                         AST_LIST_LAST(&bridge->channels)->chan);
1437         } else {
1438                 set_bridge_peer_vars_multiparty(bridge);
1439         }
1440 }
1441
1442 void bridge_reconfigured(struct ast_bridge *bridge, unsigned int colp_update)
1443 {
1444         if (!bridge->reconfigured) {
1445                 return;
1446         }
1447         bridge->reconfigured = 0;
1448         if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_SMART)
1449                 && smart_bridge_operation(bridge)) {
1450                 /* Smart bridge failed. */
1451                 bridge_dissolve(bridge, 0);
1452                 return;
1453         }
1454         bridge_complete_join(bridge);
1455
1456         if (bridge->dissolved) {
1457                 return;
1458         }
1459         check_bridge_play_sounds(bridge);
1460         set_bridge_peer_vars(bridge);
1461         ast_bridge_publish_state(bridge);
1462
1463         if (colp_update) {
1464                 bridge_reconfigured_connected_line_update(bridge);
1465         }
1466 }
1467
1468 struct ast_bridge_channel *bridge_find_channel(struct ast_bridge *bridge, struct ast_channel *chan)
1469 {
1470         struct ast_bridge_channel *bridge_channel;
1471
1472         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1473                 if (bridge_channel->chan == chan) {
1474                         break;
1475                 }
1476         }
1477
1478         return bridge_channel;
1479 }
1480
1481 void ast_bridge_notify_masquerade(struct ast_channel *chan)
1482 {
1483         struct ast_bridge_channel *bridge_channel;
1484         struct ast_bridge *bridge;
1485
1486         /* Safely get the bridge_channel pointer for the chan. */
1487         ast_channel_lock(chan);
1488         bridge_channel = ast_channel_get_bridge_channel(chan);
1489         ast_channel_unlock(chan);
1490         if (!bridge_channel) {
1491                 /* Not in a bridge */
1492                 return;
1493         }
1494
1495         ast_bridge_channel_lock_bridge(bridge_channel);
1496         bridge = bridge_channel->bridge;
1497         if (bridge_channel == bridge_find_channel(bridge, chan)) {
1498 /*
1499  * XXX ASTERISK-22366 this needs more work.  The channels need
1500  * to be made compatible again if the formats change. The
1501  * bridge_channel thread needs to monitor for this case.
1502  */
1503                 /* The channel we want to notify is still in a bridge. */
1504                 bridge->v_table->notify_masquerade(bridge, bridge_channel);
1505                 bridge_reconfigured(bridge, 1);
1506         }
1507         ast_bridge_unlock(bridge);
1508         ao2_ref(bridge_channel, -1);
1509 }
1510
1511 /*!
1512  * \brief Internal bridge impart wait condition and associated conditional.
1513  */
1514 struct bridge_channel_impart_cond {
1515         AST_LIST_ENTRY(bridge_channel_impart_cond) node;
1516         /*! Lock for the data structure */
1517         ast_mutex_t lock;
1518         /*! Wait condition */
1519         ast_cond_t cond;
1520         /*! Wait until done */
1521         int done;
1522 };
1523
1524 AST_LIST_HEAD_NOLOCK(bridge_channel_impart_ds_head, bridge_channel_impart_cond);
1525
1526 /*!
1527  * \internal
1528  * \brief Signal imparting threads to wake up.
1529  * \since 13.9.0
1530  *
1531  * \param ds_head List of imparting threads to wake up.
1532  *
1533  * \return Nothing
1534  */
1535 static void bridge_channel_impart_ds_head_signal(struct bridge_channel_impart_ds_head *ds_head)
1536 {
1537         if (ds_head) {
1538                 struct bridge_channel_impart_cond *cond;
1539
1540                 while ((cond = AST_LIST_REMOVE_HEAD(ds_head, node))) {
1541                         ast_mutex_lock(&cond->lock);
1542                         cond->done = 1;
1543                         ast_cond_signal(&cond->cond);
1544                         ast_mutex_unlock(&cond->lock);
1545                 }
1546         }
1547 }
1548
1549 static void bridge_channel_impart_ds_head_dtor(void *doomed)
1550 {
1551         bridge_channel_impart_ds_head_signal(doomed);
1552         ast_free(doomed);
1553 }
1554
1555 /*!
1556  * \internal
1557  * \brief Fixup the bridge impart datastore.
1558  * \since 13.9.0
1559  *
1560  * \param data Bridge impart datastore data to fixup from old_chan.
1561  * \param old_chan The datastore is moving from this channel.
1562  * \param new_chan The datastore is moving to this channel.
1563  *
1564  * \return Nothing
1565  */
1566 static void bridge_channel_impart_ds_head_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan)
1567 {
1568         /*
1569          * Signal any waiting impart threads.  The masquerade is going to kill
1570          * old_chan and we don't need to be waiting on new_chan.
1571          */
1572         bridge_channel_impart_ds_head_signal(data);
1573 }
1574
1575 static const struct ast_datastore_info bridge_channel_impart_ds_info = {
1576         .type = "bridge-impart-ds",
1577         .destroy = bridge_channel_impart_ds_head_dtor,
1578         .chan_fixup = bridge_channel_impart_ds_head_fixup,
1579 };
1580
1581 /*!
1582  * \internal
1583  * \brief Add impart wait datastore conditional to channel.
1584  * \since 13.9.0
1585  *
1586  * \param chan Channel to add the impart wait conditional.
1587  * \param cond Imparting conditional to add.
1588  *
1589  * \retval 0 on success.
1590  * \retval -1 on error.
1591  */
1592 static int bridge_channel_impart_add(struct ast_channel *chan, struct bridge_channel_impart_cond *cond)
1593 {
1594         struct ast_datastore *datastore;
1595         struct bridge_channel_impart_ds_head *ds_head;
1596
1597         ast_channel_lock(chan);
1598
1599         datastore = ast_channel_datastore_find(chan, &bridge_channel_impart_ds_info, NULL);
1600         if (!datastore) {
1601                 datastore = ast_datastore_alloc(&bridge_channel_impart_ds_info, NULL);
1602                 if (!datastore) {
1603                         ast_channel_unlock(chan);
1604                         return -1;
1605                 }
1606                 ds_head = ast_calloc(1, sizeof(*ds_head));
1607                 if (!ds_head) {
1608                         ast_channel_unlock(chan);
1609                         ast_datastore_free(datastore);
1610                         return -1;
1611                 }
1612                 datastore->data = ds_head;
1613                 ast_channel_datastore_add(chan, datastore);
1614         } else {
1615                 ds_head = datastore->data;
1616                 ast_assert(ds_head != NULL);
1617         }
1618
1619         AST_LIST_INSERT_TAIL(ds_head, cond, node);
1620
1621         ast_channel_unlock(chan);
1622         return 0;
1623 }
1624
1625 void bridge_channel_impart_signal(struct ast_channel *chan)
1626 {
1627         struct ast_datastore *datastore;
1628
1629         ast_channel_lock(chan);
1630         datastore = ast_channel_datastore_find(chan, &bridge_channel_impart_ds_info, NULL);
1631         if (datastore) {
1632                 bridge_channel_impart_ds_head_signal(datastore->data);
1633         }
1634         ast_channel_unlock(chan);
1635 }
1636
1637 /*!
1638  * \internal
1639  * \brief Block imparting channel thread until signaled.
1640  * \since 13.9.0
1641  *
1642  * \param cond Imparting conditional to wait for.
1643  *
1644  * \return Nothing
1645  */
1646 static void bridge_channel_impart_wait(struct bridge_channel_impart_cond *cond)
1647 {
1648         ast_mutex_lock(&cond->lock);
1649         while (!cond->done) {
1650                 ast_cond_wait(&cond->cond, &cond->lock);
1651         }
1652         ast_mutex_unlock(&cond->lock);
1653 }
1654
1655 /*
1656  * XXX ASTERISK-21271 make ast_bridge_join() require features to be allocated just like ast_bridge_impart() and not expect the struct back.
1657  *
1658  * This change is really going to break ConfBridge.  All other
1659  * users are easily changed.  However, it is needed so the
1660  * bridging code can manipulate features on all channels
1661  * consistently no matter how they joined.
1662  *
1663  * Need to update the features parameter doxygen when this
1664  * change is made to be like ast_bridge_impart().
1665  */
1666 int ast_bridge_join(struct ast_bridge *bridge,
1667         struct ast_channel *chan,
1668         struct ast_channel *swap,
1669         struct ast_bridge_features *features,
1670         struct ast_bridge_tech_optimizations *tech_args,
1671         enum ast_bridge_join_flags flags)
1672 {
1673         struct ast_bridge_channel *bridge_channel;
1674         int res = 0;
1675
1676         bridge_channel = bridge_channel_internal_alloc(bridge);
1677         if (flags & AST_BRIDGE_JOIN_PASS_REFERENCE) {
1678                 ao2_ref(bridge, -1);
1679         }
1680         if (!bridge_channel) {
1681                 ao2_t_cleanup(swap, "Error exit: bridge_channel alloc failed");
1682                 res = -1;
1683                 goto join_exit;
1684         }
1685 /* XXX ASTERISK-21271 features cannot be NULL when passed in. When it is changed to allocated we can do like ast_bridge_impart() and allocate one. */
1686         ast_assert(features != NULL);
1687         if (!features) {
1688                 ao2_ref(bridge_channel, -1);
1689                 ao2_t_cleanup(swap, "Error exit: features is NULL");
1690                 res = -1;
1691                 goto join_exit;
1692         }
1693         if (tech_args) {
1694                 bridge_channel->tech_args = *tech_args;
1695         }
1696
1697         ast_channel_lock(chan);
1698         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE)) {
1699                 res = -1;
1700         } else {
1701                 ast_channel_internal_bridge_channel_set(chan, bridge_channel);
1702         }
1703         ast_channel_unlock(chan);
1704         bridge_channel->thread = pthread_self();
1705         bridge_channel->chan = chan;
1706         bridge_channel->swap = swap;
1707         bridge_channel->features = features;
1708         bridge_channel->inhibit_colp = !!(flags & AST_BRIDGE_JOIN_INHIBIT_JOIN_COLP);
1709
1710         /* allow subclass to peek at upcoming push operation */
1711         if (bridge->v_table->push_peek && !res) {
1712                 struct ast_bridge_channel *bcswap = NULL;
1713
1714                 ast_bridge_lock(bridge);
1715                 if (bridge_channel->swap) {
1716                         bcswap = bridge_find_channel(bridge, bridge_channel->swap);
1717                 }
1718                 res = bridge->v_table->push_peek(bridge, bridge_channel, bcswap);
1719                 ast_bridge_unlock(bridge);
1720         }
1721
1722         if (!res) {
1723                 res = bridge_channel_internal_join(bridge_channel);
1724         }
1725
1726         /* Cleanup all the data in the bridge channel after it leaves the bridge. */
1727         ast_channel_lock(chan);
1728         ast_channel_internal_bridge_channel_set(chan, NULL);
1729         ast_channel_unlock(chan);
1730         bridge_channel->chan = NULL;
1731         /* If bridge_channel->swap is not NULL then the join failed. */
1732         ao2_t_cleanup(bridge_channel->swap, "Bridge complete: join failed");
1733         bridge_channel->swap = NULL;
1734         bridge_channel->features = NULL;
1735
1736         ao2_ref(bridge_channel, -1);
1737
1738 join_exit:;
1739         ast_bridge_run_after_callback(chan);
1740         bridge_channel_impart_signal(chan);
1741         if (!(ast_channel_softhangup_internal_flag(chan) & AST_SOFTHANGUP_ASYNCGOTO)
1742                 && !ast_bridge_setup_after_goto(chan)) {
1743                 /* Claim the after bridge goto is an async goto destination. */
1744                 ast_channel_lock(chan);
1745                 ast_softhangup_nolock(chan, AST_SOFTHANGUP_ASYNCGOTO);
1746                 ast_channel_unlock(chan);
1747         }
1748         return res;
1749 }
1750
1751 /*! \brief Thread responsible for imparted bridged channels to be departed */
1752 static void *bridge_channel_depart_thread(void *data)
1753 {
1754         struct ast_bridge_channel *bridge_channel = data;
1755
1756         if (bridge_channel->callid) {
1757                 ast_callid_threadassoc_add(bridge_channel->callid);
1758         }
1759
1760         bridge_channel_internal_join(bridge_channel);
1761
1762         /*
1763          * cleanup
1764          *
1765          * If bridge_channel->swap is not NULL then the join failed.
1766          */
1767         ao2_t_cleanup(bridge_channel->swap, "Bridge complete: Departable impart join failed");
1768         bridge_channel->swap = NULL;
1769         ast_bridge_features_destroy(bridge_channel->features);
1770         bridge_channel->features = NULL;
1771
1772         ast_bridge_discard_after_callback(bridge_channel->chan, AST_BRIDGE_AFTER_CB_REASON_DEPART);
1773         /* If join failed there will be impart threads waiting. */
1774         bridge_channel_impart_signal(bridge_channel->chan);
1775         ast_bridge_discard_after_goto(bridge_channel->chan);
1776
1777         return NULL;
1778 }
1779
1780 /*! \brief Thread responsible for independent imparted bridged channels */
1781 static void *bridge_channel_ind_thread(void *data)
1782 {
1783         struct ast_bridge_channel *bridge_channel = data;
1784         struct ast_channel *chan;
1785
1786         if (bridge_channel->callid) {
1787                 ast_callid_threadassoc_add(bridge_channel->callid);
1788         }
1789
1790         bridge_channel_internal_join(bridge_channel);
1791         chan = bridge_channel->chan;
1792
1793         /* cleanup */
1794         ast_channel_lock(chan);
1795         ast_channel_internal_bridge_channel_set(chan, NULL);
1796         ast_channel_unlock(chan);
1797         bridge_channel->chan = NULL;
1798         /* If bridge_channel->swap is not NULL then the join failed. */
1799         ao2_t_cleanup(bridge_channel->swap, "Bridge complete: Independent impart join failed");
1800         bridge_channel->swap = NULL;
1801         ast_bridge_features_destroy(bridge_channel->features);
1802         bridge_channel->features = NULL;
1803
1804         ao2_ref(bridge_channel, -1);
1805
1806         ast_bridge_run_after_callback(chan);
1807         /* If join failed there will be impart threads waiting. */
1808         bridge_channel_impart_signal(chan);
1809         ast_bridge_run_after_goto(chan);
1810         return NULL;
1811 }
1812
1813 static int bridge_impart_internal(struct ast_bridge *bridge,
1814         struct ast_channel *chan,
1815         struct ast_channel *swap,
1816         struct ast_bridge_features *features,
1817         enum ast_bridge_impart_flags flags,
1818         struct bridge_channel_impart_cond *cond)
1819 {
1820         int res = 0;
1821         struct ast_bridge_channel *bridge_channel;
1822
1823         /* Imparted channels cannot have a PBX. */
1824         if (ast_channel_pbx(chan)) {
1825                 ast_log(AST_LOG_WARNING, "Channel %s has a PBX thread and cannot be imparted into bridge %s\n",
1826                         ast_channel_name(chan), bridge->uniqueid);
1827                 ast_bridge_features_destroy(features);
1828                 return -1;
1829         }
1830
1831         /* Supply an empty features structure if the caller did not. */
1832         if (!features) {
1833                 features = ast_bridge_features_new();
1834                 if (!features) {
1835                         return -1;
1836                 }
1837         }
1838
1839         /* Try to allocate a structure for the bridge channel */
1840         bridge_channel = bridge_channel_internal_alloc(bridge);
1841         if (!bridge_channel) {
1842                 ast_bridge_features_destroy(features);
1843                 return -1;
1844         }
1845
1846         ast_channel_lock(chan);
1847         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE)) {
1848                 ast_log(AST_LOG_NOTICE, "Channel %s is a zombie and cannot be imparted into bridge %s\n",
1849                         ast_channel_name(chan), bridge->uniqueid);
1850                 res = -1;
1851         } else {
1852                 ast_channel_internal_bridge_channel_set(chan, bridge_channel);
1853         }
1854         ast_channel_unlock(chan);
1855         bridge_channel->chan = chan;
1856         bridge_channel->swap = ao2_t_bump(swap, "Setting up bridge impart");
1857         bridge_channel->features = features;
1858         bridge_channel->inhibit_colp = !!(flags & AST_BRIDGE_IMPART_INHIBIT_JOIN_COLP);
1859         bridge_channel->depart_wait =
1860                 (flags & AST_BRIDGE_IMPART_CHAN_MASK) == AST_BRIDGE_IMPART_CHAN_DEPARTABLE;
1861         bridge_channel->callid = ast_read_threadstorage_callid();
1862
1863         /* allow subclass to peek at swap channel before it can hangup */
1864         if (bridge->v_table->push_peek && !res) {
1865                 struct ast_bridge_channel *bcswap = NULL;
1866
1867                 ast_bridge_lock(bridge);
1868                 if (bridge_channel->swap) {
1869                         bcswap = bridge_find_channel(bridge, bridge_channel->swap);
1870                 }
1871                 res = bridge->v_table->push_peek(bridge, bridge_channel, bcswap);
1872                 ast_bridge_unlock(bridge);
1873         }
1874
1875         /* Actually create the thread that will handle the channel */
1876         if (!res) {
1877                 res = bridge_channel_impart_add(chan, cond);
1878         }
1879         if (!res) {
1880                 if ((flags & AST_BRIDGE_IMPART_CHAN_MASK) == AST_BRIDGE_IMPART_CHAN_INDEPENDENT) {
1881                         res = ast_pthread_create_detached(&bridge_channel->thread, NULL,
1882                                 bridge_channel_ind_thread, bridge_channel);
1883                 } else {
1884                         res = ast_pthread_create(&bridge_channel->thread, NULL,
1885                                 bridge_channel_depart_thread, bridge_channel);
1886                 }
1887
1888                 if (!res) {
1889                         bridge_channel_impart_wait(cond);
1890                 }
1891         }
1892
1893         if (res) {
1894                 /* cleanup */
1895                 ast_channel_lock(chan);
1896                 ast_channel_internal_bridge_channel_set(chan, NULL);
1897                 ast_channel_unlock(chan);
1898                 bridge_channel->chan = NULL;
1899                 ao2_t_cleanup(bridge_channel->swap, "Bridge complete: Impart failed");
1900                 bridge_channel->swap = NULL;
1901                 ast_bridge_features_destroy(bridge_channel->features);
1902                 bridge_channel->features = NULL;
1903
1904                 ao2_ref(bridge_channel, -1);
1905                 return -1;
1906         }
1907
1908         return 0;
1909 }
1910
1911 int ast_bridge_impart(struct ast_bridge *bridge,
1912         struct ast_channel *chan,
1913         struct ast_channel *swap,
1914         struct ast_bridge_features *features,
1915         enum ast_bridge_impart_flags flags)
1916 {
1917         struct bridge_channel_impart_cond cond = {
1918                 .done = 0,
1919         };
1920         int res;
1921
1922         ast_mutex_init(&cond.lock);
1923         ast_cond_init(&cond.cond, NULL);
1924
1925         res = bridge_impart_internal(bridge, chan, swap, features, flags, &cond);
1926         if (res) {
1927                 /* Impart failed.  Signal any other waiting impart threads */
1928                 bridge_channel_impart_signal(chan);
1929         }
1930
1931         ast_cond_destroy(&cond.cond);
1932         ast_mutex_destroy(&cond.lock);
1933
1934         return res;
1935 }
1936
1937 int ast_bridge_depart(struct ast_channel *chan)
1938 {
1939         struct ast_bridge_channel *bridge_channel;
1940         int departable;
1941
1942         ast_channel_lock(chan);
1943         bridge_channel = ast_channel_internal_bridge_channel(chan);
1944         departable = bridge_channel && bridge_channel->depart_wait;
1945         ast_channel_unlock(chan);
1946         if (!departable) {
1947                 ast_log(LOG_ERROR, "Channel %s cannot be departed.\n",
1948                         ast_channel_name(chan));
1949                 /*
1950                  * Should never happen.  It likely means that
1951                  * ast_bridge_depart() is called by two threads for the same
1952                  * channel, the channel was never imparted to be departed, or it
1953                  * has already been departed.
1954                  */
1955                 ast_assert(0);
1956                 return -1;
1957         }
1958
1959         /*
1960          * We are claiming the bridge_channel reference held by
1961          * bridge_channel_depart_thread().
1962          */
1963
1964         ast_bridge_channel_leave_bridge(bridge_channel,
1965                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
1966
1967         /* Wait for the depart thread to die */
1968         ast_debug(1, "Waiting for %p(%s) bridge thread to die.\n",
1969                 bridge_channel, ast_channel_name(bridge_channel->chan));
1970         pthread_join(bridge_channel->thread, NULL);
1971
1972         ast_channel_lock(chan);
1973         ast_channel_internal_bridge_channel_set(chan, NULL);
1974         ast_channel_unlock(chan);
1975
1976         /* We can get rid of the bridge_channel after the depart thread has died. */
1977         ao2_ref(bridge_channel, -1);
1978         return 0;
1979 }
1980
1981 int ast_bridge_remove(struct ast_bridge *bridge, struct ast_channel *chan)
1982 {
1983         struct ast_bridge_channel *bridge_channel;
1984
1985         ast_bridge_lock(bridge);
1986
1987         /* Try to find the channel that we want to remove */
1988         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
1989                 ast_bridge_unlock(bridge);
1990                 return -1;
1991         }
1992
1993         ast_bridge_channel_leave_bridge(bridge_channel,
1994                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
1995
1996         ast_bridge_unlock(bridge);
1997
1998         return 0;
1999 }
2000
2001 static void kick_it(struct ast_bridge_channel *bridge_channel, const void *payload, size_t payload_size)
2002 {
2003         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
2004 }
2005
2006 int ast_bridge_kick(struct ast_bridge *bridge, struct ast_channel *chan)
2007 {
2008         struct ast_bridge_channel *bridge_channel;
2009         int res;
2010
2011         ast_bridge_lock(bridge);
2012
2013         /* Try to find the channel that we want to kick. */
2014         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
2015                 ast_bridge_unlock(bridge);
2016                 return -1;
2017         }
2018
2019         res = ast_bridge_channel_queue_callback(bridge_channel, 0, kick_it, NULL, 0);
2020
2021         ast_bridge_unlock(bridge);
2022
2023         return res;
2024 }
2025
2026 /*!
2027  * \internal
2028  * \brief Point the bridge_channel to a new bridge.
2029  * \since 12.0.0
2030  *
2031  * \param bridge_channel What is to point to a new bridge.
2032  * \param new_bridge Where the bridge channel should point.
2033  *
2034  * \return Nothing
2035  */
2036 static void bridge_channel_change_bridge(struct ast_bridge_channel *bridge_channel, struct ast_bridge *new_bridge)
2037 {
2038         struct ast_bridge *old_bridge;
2039
2040         ao2_ref(new_bridge, +1);
2041         ast_bridge_channel_lock(bridge_channel);
2042         ast_channel_lock(bridge_channel->chan);
2043         old_bridge = bridge_channel->bridge;
2044         bridge_channel->bridge = new_bridge;
2045         ast_channel_internal_bridge_set(bridge_channel->chan, new_bridge);
2046         ast_channel_unlock(bridge_channel->chan);
2047         ast_bridge_channel_unlock(bridge_channel);
2048         ao2_ref(old_bridge, -1);
2049 }
2050
2051 static void bridge_channel_moving(struct ast_bridge_channel *bridge_channel, struct ast_bridge *src, struct ast_bridge *dst)
2052 {
2053         struct ast_bridge_features *features = bridge_channel->features;
2054         struct ast_bridge_hook *hook;
2055         struct ao2_iterator iter;
2056
2057         /* Run any moving hooks. */
2058         iter = ao2_iterator_init(features->other_hooks, 0);
2059         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
2060                 int remove_me;
2061                 ast_bridge_move_indicate_callback move_cb;
2062
2063                 if (hook->type != AST_BRIDGE_HOOK_TYPE_MOVE) {
2064                         continue;
2065                 }
2066                 move_cb = (ast_bridge_move_indicate_callback) hook->callback;
2067                 remove_me = move_cb(bridge_channel, hook->hook_pvt, src, dst);
2068                 if (remove_me) {
2069                         ast_debug(1, "Move detection hook %p is being removed from %p(%s)\n",
2070                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
2071                         ao2_unlink(features->other_hooks, hook);
2072                 }
2073         }
2074         ao2_iterator_destroy(&iter);
2075 }
2076
2077 void bridge_do_merge(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, struct ast_bridge_channel **kick_me, unsigned int num_kick,
2078         unsigned int optimized)
2079 {
2080         struct ast_bridge_channel *bridge_channel;
2081         unsigned int idx;
2082
2083         ast_debug(1, "Merging bridge %s into bridge %s\n",
2084                 src_bridge->uniqueid, dst_bridge->uniqueid);
2085
2086         ast_bridge_publish_merge(dst_bridge, src_bridge);
2087
2088         /*
2089          * Move channels from src_bridge over to dst_bridge.
2090          *
2091          * We must use AST_LIST_TRAVERSE_SAFE_BEGIN() because
2092          * bridge_channel_internal_pull() alters the list we are traversing.
2093          */
2094         AST_LIST_TRAVERSE_SAFE_BEGIN(&src_bridge->channels, bridge_channel, entry) {
2095                 if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2096                         /*
2097                          * The channel is already leaving let it leave normally because
2098                          * pulling it may delete hooks that should run for this channel.
2099                          */
2100                         continue;
2101                 }
2102                 if (ast_test_flag(&bridge_channel->features->feature_flags,
2103                         AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
2104                         continue;
2105                 }
2106
2107                 if (kick_me) {
2108                         for (idx = 0; idx < num_kick; ++idx) {
2109                                 if (bridge_channel == kick_me[idx]) {
2110                                         ast_bridge_channel_leave_bridge(bridge_channel,
2111                                                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
2112                                         break;
2113                                 }
2114                         }
2115                 }
2116                 bridge_channel_internal_pull(bridge_channel);
2117                 if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2118                         /*
2119                          * The channel died as a result of being pulled or it was
2120                          * kicked.  Leave it pointing to the original bridge.
2121                          */
2122                         continue;
2123                 }
2124
2125                 bridge_channel_moving(bridge_channel, bridge_channel->bridge, dst_bridge);
2126
2127                 /* Point to new bridge.*/
2128                 bridge_channel_change_bridge(bridge_channel, dst_bridge);
2129
2130                 if (bridge_channel_internal_push(bridge_channel)) {
2131                         ast_bridge_features_remove(bridge_channel->features,
2132                                 AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2133                         ast_bridge_channel_leave_bridge(bridge_channel,
2134                                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
2135                 }
2136         }
2137         AST_LIST_TRAVERSE_SAFE_END;
2138
2139         if (kick_me) {
2140                 /*
2141                  * Now we can kick any channels in the dst_bridge without
2142                  * potentially dissolving the bridge.
2143                  */
2144                 for (idx = 0; idx < num_kick; ++idx) {
2145                         bridge_channel = kick_me[idx];
2146                         ast_bridge_channel_lock(bridge_channel);
2147                         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2148                                 ast_bridge_channel_leave_bridge_nolock(bridge_channel,
2149                                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
2150                                 bridge_channel_internal_pull(bridge_channel);
2151                         }
2152                         ast_bridge_channel_unlock(bridge_channel);
2153                 }
2154         }
2155
2156         bridge_reconfigured(dst_bridge, !optimized);
2157         bridge_reconfigured(src_bridge, !optimized);
2158
2159         ast_debug(1, "Merged bridge %s into bridge %s\n",
2160                 src_bridge->uniqueid, dst_bridge->uniqueid);
2161 }
2162
2163 struct merge_direction {
2164         /*! Destination merge bridge. */
2165         struct ast_bridge *dest;
2166         /*! Source merge bridge. */
2167         struct ast_bridge *src;
2168 };
2169
2170 /*!
2171  * \internal
2172  * \brief Determine which bridge should merge into the other.
2173  * \since 12.0.0
2174  *
2175  * \param bridge1 A bridge for merging
2176  * \param bridge2 A bridge for merging
2177  *
2178  * \note The two bridges are assumed already locked.
2179  *
2180  * \return Which bridge merges into which or NULL bridges if cannot merge.
2181  */
2182 static struct merge_direction bridge_merge_determine_direction(struct ast_bridge *bridge1, struct ast_bridge *bridge2)
2183 {
2184         struct merge_direction merge = { NULL, NULL };
2185         int bridge1_priority;
2186         int bridge2_priority;
2187
2188         if (!ast_test_flag(&bridge1->feature_flags,
2189                         AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)
2190                 && !ast_test_flag(&bridge2->feature_flags,
2191                         AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
2192                 /*
2193                  * Can merge either way.  Merge to the higher priority merge
2194                  * bridge.  Otherwise merge to the larger bridge.
2195                  */
2196                 bridge1_priority = bridge1->v_table->get_merge_priority(bridge1);
2197                 bridge2_priority = bridge2->v_table->get_merge_priority(bridge2);
2198                 if (bridge2_priority < bridge1_priority) {
2199                         merge.dest = bridge1;
2200                         merge.src = bridge2;
2201                 } else if (bridge1_priority < bridge2_priority) {
2202                         merge.dest = bridge2;
2203                         merge.src = bridge1;
2204                 } else {
2205                         /* Merge to the larger bridge. */
2206                         if (bridge2->num_channels <= bridge1->num_channels) {
2207                                 merge.dest = bridge1;
2208                                 merge.src = bridge2;
2209                         } else {
2210                                 merge.dest = bridge2;
2211                                 merge.src = bridge1;
2212                         }
2213                 }
2214         } else if (!ast_test_flag(&bridge1->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
2215                 && !ast_test_flag(&bridge2->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
2216                 /* Can merge only one way. */
2217                 merge.dest = bridge1;
2218                 merge.src = bridge2;
2219         } else if (!ast_test_flag(&bridge2->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
2220                 && !ast_test_flag(&bridge1->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
2221                 /* Can merge only one way. */
2222                 merge.dest = bridge2;
2223                 merge.src = bridge1;
2224         }
2225
2226         return merge;
2227 }
2228
2229 /*!
2230  * \internal
2231  * \brief Merge two bridges together
2232  * \since 12.0.0
2233  *
2234  * \param dst_bridge Destination bridge of merge.
2235  * \param src_bridge Source bridge of merge.
2236  * \param merge_best_direction TRUE if don't care about which bridge merges into the other.
2237  * \param kick_me Array of channels to kick from the bridges.
2238  * \param num_kick Number of channels in the kick_me array.
2239  *
2240  * \note The dst_bridge and src_bridge are assumed already locked.
2241  *
2242  * \retval 0 on success
2243  * \retval -1 on failure
2244  */
2245 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)
2246 {
2247         struct merge_direction merge;
2248         struct ast_bridge_channel **kick_them = NULL;
2249
2250         /* Sanity check. */
2251         ast_assert(dst_bridge && src_bridge && dst_bridge != src_bridge && (!num_kick || kick_me));
2252
2253         if (dst_bridge->dissolved || src_bridge->dissolved) {
2254                 ast_debug(1, "Can't merge bridges %s and %s, at least one bridge is dissolved.\n",
2255                         src_bridge->uniqueid, dst_bridge->uniqueid);
2256                 return -1;
2257         }
2258         if (ast_test_flag(&dst_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)
2259                 || ast_test_flag(&src_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
2260                 ast_debug(1, "Can't merge bridges %s and %s, masquerade only.\n",
2261                         src_bridge->uniqueid, dst_bridge->uniqueid);
2262                 return -1;
2263         }
2264         if (dst_bridge->inhibit_merge || src_bridge->inhibit_merge) {
2265                 ast_debug(1, "Can't merge bridges %s and %s, merging temporarily inhibited.\n",
2266                         src_bridge->uniqueid, dst_bridge->uniqueid);
2267                 return -1;
2268         }
2269
2270         if (merge_best_direction) {
2271                 merge = bridge_merge_determine_direction(dst_bridge, src_bridge);
2272         } else {
2273                 merge.dest = dst_bridge;
2274                 merge.src = src_bridge;
2275         }
2276
2277         if (!merge.dest
2278                 || ast_test_flag(&merge.dest->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
2279                 || ast_test_flag(&merge.src->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
2280                 ast_debug(1, "Can't merge bridges %s and %s, merging inhibited.\n",
2281                         src_bridge->uniqueid, dst_bridge->uniqueid);
2282                 return -1;
2283         }
2284         if (merge.src->num_channels < 2) {
2285                 /*
2286                  * For a two party bridge, a channel may be temporarily removed
2287                  * from the source bridge or the initial bridge members have not
2288                  * joined yet.
2289                  */
2290                 ast_debug(1, "Can't merge bridge %s into bridge %s, not enough channels in source bridge.\n",
2291                         merge.src->uniqueid, merge.dest->uniqueid);
2292                 return -1;
2293         }
2294         if (2 + num_kick < merge.dest->num_channels + merge.src->num_channels
2295                 && !(merge.dest->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)
2296                 && (!ast_test_flag(&merge.dest->feature_flags, AST_BRIDGE_FLAG_SMART)
2297                         || !(merge.dest->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX))) {
2298                 ast_debug(1, "Can't merge bridge %s into bridge %s, multimix is needed and it cannot be acquired.\n",
2299                         merge.src->uniqueid, merge.dest->uniqueid);
2300                 return -1;
2301         }
2302
2303         if (num_kick) {
2304                 unsigned int num_to_kick = 0;
2305                 unsigned int idx;
2306
2307                 kick_them = ast_alloca(num_kick * sizeof(*kick_them));
2308                 for (idx = 0; idx < num_kick; ++idx) {
2309                         kick_them[num_to_kick] = bridge_find_channel(merge.src, kick_me[idx]);
2310                         if (!kick_them[num_to_kick]) {
2311                                 kick_them[num_to_kick] = bridge_find_channel(merge.dest, kick_me[idx]);
2312                         }
2313                         if (kick_them[num_to_kick]) {
2314                                 ++num_to_kick;
2315                         }
2316                 }
2317
2318                 if (num_to_kick != num_kick) {
2319                         ast_debug(1, "Can't merge bridge %s into bridge %s, at least one kicked channel is not in either bridge.\n",
2320                                 merge.src->uniqueid, merge.dest->uniqueid);
2321                         return -1;
2322                 }
2323         }
2324
2325         bridge_do_merge(merge.dest, merge.src, kick_them, num_kick, 0);
2326         return 0;
2327 }
2328
2329 int ast_bridge_merge(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, int merge_best_direction, struct ast_channel **kick_me, unsigned int num_kick)
2330 {
2331         int res;
2332
2333         /* Sanity check. */
2334         ast_assert(dst_bridge && src_bridge);
2335
2336         ast_bridge_lock_both(dst_bridge, src_bridge);
2337         res = bridge_merge_locked(dst_bridge, src_bridge, merge_best_direction, kick_me, num_kick);
2338         ast_bridge_unlock(src_bridge);
2339         ast_bridge_unlock(dst_bridge);
2340         return res;
2341 }
2342
2343 int bridge_do_move(struct ast_bridge *dst_bridge, struct ast_bridge_channel *bridge_channel, int attempt_recovery,
2344         unsigned int optimized)
2345 {
2346         struct ast_bridge *orig_bridge;
2347         int was_in_bridge;
2348         int res = 0;
2349
2350         if (bridge_channel->swap) {
2351                 ast_debug(1, "Moving %p(%s) into bridge %s swapping with %s\n",
2352                         bridge_channel, ast_channel_name(bridge_channel->chan), dst_bridge->uniqueid,
2353                         ast_channel_name(bridge_channel->swap));
2354         } else {
2355                 ast_debug(1, "Moving %p(%s) into bridge %s\n",
2356                         bridge_channel, ast_channel_name(bridge_channel->chan), dst_bridge->uniqueid);
2357         }
2358
2359         orig_bridge = bridge_channel->bridge;
2360         was_in_bridge = bridge_channel->in_bridge;
2361
2362         bridge_channel_internal_pull(bridge_channel);
2363         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2364                 /*
2365                  * The channel died as a result of being pulled.  Leave it
2366                  * pointing to the original bridge.
2367                  *
2368                  * Clear out the swap channel pointer.  A ref is not held
2369                  * by bridge_channel->swap at this point.
2370                  */
2371                 bridge_channel->swap = NULL;
2372                 bridge_reconfigured(orig_bridge, 0);
2373                 return -1;
2374         }
2375
2376         /* Point to new bridge.*/
2377         ao2_ref(orig_bridge, +1);/* Keep a ref in case the push fails. */
2378         bridge_channel_change_bridge(bridge_channel, dst_bridge);
2379
2380         bridge_channel_moving(bridge_channel, orig_bridge, dst_bridge);
2381
2382         if (bridge_channel_internal_push_full(bridge_channel, optimized)) {
2383                 /* Try to put the channel back into the original bridge. */
2384                 ast_bridge_features_remove(bridge_channel->features,
2385                         AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2386                 if (attempt_recovery && was_in_bridge) {
2387                         /* Point back to original bridge. */
2388                         bridge_channel_change_bridge(bridge_channel, orig_bridge);
2389
2390                         if (bridge_channel_internal_push(bridge_channel)) {
2391                                 ast_bridge_features_remove(bridge_channel->features,
2392                                         AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2393                                 ast_bridge_channel_leave_bridge(bridge_channel,
2394                                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
2395                         }
2396                 } else {
2397                         ast_bridge_channel_leave_bridge(bridge_channel,
2398                                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
2399                         bridge_channel_settle_owed_events(orig_bridge, bridge_channel);
2400                 }
2401                 res = -1;
2402         } else if (!optimized) {
2403                 bridge_channel_settle_owed_events(orig_bridge, bridge_channel);
2404         }
2405
2406         bridge_reconfigured(dst_bridge, !optimized);
2407         bridge_reconfigured(orig_bridge, !optimized);
2408         ao2_ref(orig_bridge, -1);
2409         return res;
2410 }
2411
2412 /*!
2413  * \internal
2414  * \brief Move a channel from one bridge to another.
2415  * \since 12.0.0
2416  *
2417  * \param dst_bridge Destination bridge of bridge channel move.
2418  * \param src_bridge Source bridge of bridge channel move.
2419  * \param chan Channel to move.
2420  * \param swap Channel to replace in dst_bridge.
2421  * \param attempt_recovery TRUE if failure attempts to push channel back into original bridge.
2422  *
2423  * \note The dst_bridge and src_bridge are assumed already locked.
2424  *
2425  * \retval 0 on success.
2426  * \retval -1 on failure.
2427  */
2428 static int bridge_move_locked(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, struct ast_channel *chan, struct ast_channel *swap, int attempt_recovery)
2429 {
2430         struct ast_bridge_channel *bridge_channel;
2431
2432         if (dst_bridge->dissolved || src_bridge->dissolved) {
2433                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, at least one bridge is dissolved.\n",
2434                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2435                 return -1;
2436         }
2437         if (ast_test_flag(&dst_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)
2438                 || ast_test_flag(&src_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
2439                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, masquerade only.\n",
2440                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2441                 return -1;
2442         }
2443         if (dst_bridge->inhibit_merge || src_bridge->inhibit_merge) {
2444                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, temporarily inhibited.\n",
2445                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2446                 return -1;
2447         }
2448
2449         bridge_channel = bridge_find_channel(src_bridge, chan);
2450         if (!bridge_channel) {
2451                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel not in bridge.\n",
2452                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2453                 return -1;
2454         }
2455         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2456                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel leaving bridge.\n",
2457                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2458                 return -1;
2459         }
2460         if (ast_test_flag(&bridge_channel->features->feature_flags,
2461                 AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
2462                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel immovable.\n",
2463                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2464                 return -1;
2465         }
2466
2467         if (swap) {
2468                 struct ast_bridge_channel *bridge_channel_swap;
2469
2470                 bridge_channel_swap = bridge_find_channel(dst_bridge, swap);
2471                 if (!bridge_channel_swap) {
2472                         ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, swap channel %s not in bridge.\n",
2473                                 ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid,
2474                                 ast_channel_name(swap));
2475                         return -1;
2476                 }
2477                 if (bridge_channel_swap->state != BRIDGE_CHANNEL_STATE_WAIT) {
2478                         ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, swap channel %s leaving bridge.\n",
2479                                 ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid,
2480                                 ast_channel_name(swap));
2481                         return -1;
2482                 }
2483         }
2484
2485         bridge_channel->swap = swap;
2486         return bridge_do_move(dst_bridge, bridge_channel, attempt_recovery, 0);
2487 }
2488
2489 int ast_bridge_move(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, struct ast_channel *chan, struct ast_channel *swap, int attempt_recovery)
2490 {
2491         int res;
2492
2493         ast_bridge_lock_both(dst_bridge, src_bridge);
2494         res = bridge_move_locked(dst_bridge, src_bridge, chan, swap, attempt_recovery);
2495         ast_bridge_unlock(src_bridge);
2496         ast_bridge_unlock(dst_bridge);
2497         return res;
2498 }
2499
2500 int ast_bridge_add_channel(struct ast_bridge *bridge, struct ast_channel *chan,
2501         struct ast_bridge_features *features, int play_tone, const char *xfersound)
2502 {
2503         RAII_VAR(struct ast_bridge *, chan_bridge, NULL, ao2_cleanup);
2504         RAII_VAR(struct ast_channel *, yanked_chan, NULL, ao2_cleanup);
2505
2506         ast_channel_lock(chan);
2507         chan_bridge = ast_channel_get_bridge(chan);
2508         ast_channel_unlock(chan);
2509
2510         if (chan_bridge) {
2511                 struct ast_bridge_channel *bridge_channel;
2512
2513                 /* The channel is in a bridge so it is not getting any new features. */
2514                 ast_bridge_features_destroy(features);
2515
2516                 ast_bridge_lock_both(bridge, chan_bridge);
2517                 bridge_channel = bridge_find_channel(chan_bridge, chan);
2518
2519                 if (bridge_move_locked(bridge, chan_bridge, chan, NULL, 1)) {
2520                         ast_bridge_unlock(chan_bridge);
2521                         ast_bridge_unlock(bridge);
2522                         return -1;
2523                 }
2524
2525                 /*
2526                  * bridge_move_locked() will implicitly ensure that
2527                  * bridge_channel is not NULL.
2528                  */
2529                 ast_assert(bridge_channel != NULL);
2530
2531                 /*
2532                  * Additional checks if the channel we just stole dissolves the
2533                  * original bridge.
2534                  */
2535                 bridge_dissolve_check_stolen(chan_bridge, bridge_channel);
2536                 ast_bridge_unlock(chan_bridge);
2537                 ast_bridge_unlock(bridge);
2538         } else {
2539                 /* Slightly less easy case. We need to yank channel A from
2540                  * where he currently is and impart him into our bridge.
2541                  */
2542                 yanked_chan = ast_channel_yank(chan);
2543                 if (!yanked_chan) {
2544                         ast_log(LOG_WARNING, "Could not gain control of channel %s\n", ast_channel_name(chan));
2545                         ast_bridge_features_destroy(features);
2546                         return -1;
2547                 }
2548                 if (ast_channel_state(yanked_chan) != AST_STATE_UP) {
2549                         ast_answer(yanked_chan);
2550                 }
2551                 ast_channel_ref(yanked_chan);
2552                 if (ast_bridge_impart(bridge, yanked_chan, NULL, features,
2553                         AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
2554                         /* It is possible for us to yank a channel and have some other
2555                          * thread start a PBX on the channl after we yanked it. In particular,
2556                          * this can theoretically happen on the ;2 of a Local channel if we
2557                          * yank it prior to the ;1 being answered. Make sure that it isn't
2558                          * executing a PBX before hanging it up.
2559                          */
2560                         if (ast_channel_pbx(yanked_chan)) {
2561                                 ast_channel_unref(yanked_chan);
2562                         } else {
2563                                 ast_hangup(yanked_chan);
2564                         }
2565                         return -1;
2566                 }
2567         }
2568
2569         if (play_tone && !ast_strlen_zero(xfersound)) {
2570                 struct ast_channel *play_chan = yanked_chan ?: chan;
2571                 RAII_VAR(struct ast_bridge_channel *, play_bridge_channel, NULL, ao2_cleanup);
2572
2573                 ast_channel_lock(play_chan);
2574                 play_bridge_channel = ast_channel_get_bridge_channel(play_chan);
2575                 ast_channel_unlock(play_chan);
2576
2577                 if (!play_bridge_channel) {
2578                         ast_log(LOG_WARNING, "Unable to play tone for channel %s. No longer in a bridge.\n",
2579                                 ast_channel_name(play_chan));
2580                 } else {
2581                         ast_bridge_channel_queue_playfile(play_bridge_channel, NULL, xfersound, NULL);
2582                 }
2583         }
2584         return 0;
2585 }
2586
2587 static int bridge_allows_optimization(struct ast_bridge *bridge)
2588 {
2589         return !(bridge->inhibit_merge
2590                 || bridge->dissolved
2591                 || ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY));
2592 }
2593
2594 /*!
2595  * \internal
2596  * \brief Lock the unreal channel stack for chan and prequalify it.
2597  * \since 12.0.0
2598  *
2599  * \param chan Unreal channel writing a frame into the channel driver.
2600  *
2601  * \note It is assumed that chan is already locked.
2602  *
2603  * \retval bridge on success with bridge and bridge_channel locked.
2604  * \retval NULL if cannot do optimization now.
2605  */
2606 static struct ast_bridge *optimize_lock_chan_stack(struct ast_channel *chan)
2607 {
2608         struct ast_bridge *bridge;
2609         struct ast_bridge_channel *bridge_channel;
2610
2611         if (!AST_LIST_EMPTY(ast_channel_readq(chan))) {
2612                 return NULL;
2613         }
2614         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF)) {
2615                 return NULL;
2616         }
2617         if (ast_channel_has_audio_frame_or_monitor(chan)) {
2618                 /* Channel has an active monitor, audiohook, or framehook. */
2619                 return NULL;
2620         }
2621         bridge_channel = ast_channel_internal_bridge_channel(chan);
2622         if (!bridge_channel || ast_bridge_channel_trylock(bridge_channel)) {
2623                 return NULL;
2624         }
2625         bridge = bridge_channel->bridge;
2626         if (bridge_channel->activity != BRIDGE_CHANNEL_THREAD_SIMPLE
2627                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2628                 || ast_bridge_trylock(bridge)) {
2629                 ast_bridge_channel_unlock(bridge_channel);
2630                 return NULL;
2631         }
2632         if (!bridge_channel_internal_allows_optimization(bridge_channel) ||
2633                         !bridge_allows_optimization(bridge)) {
2634                 ast_bridge_unlock(bridge);
2635                 ast_bridge_channel_unlock(bridge_channel);
2636                 return NULL;
2637         }
2638         return bridge;
2639 }
2640
2641 /*!
2642  * \internal
2643  * \brief Lock the unreal channel stack for peer and prequalify it.
2644  * \since 12.0.0
2645  *
2646  * \param peer Other unreal channel in the pair.
2647  *
2648  * \retval bridge on success with bridge, bridge_channel, and peer locked.
2649  * \retval NULL if cannot do optimization now.
2650  */
2651 static struct ast_bridge *optimize_lock_peer_stack(struct ast_channel *peer)
2652 {
2653         struct ast_bridge *bridge;
2654         struct ast_bridge_channel *bridge_channel;
2655
2656         if (ast_channel_trylock(peer)) {
2657                 return NULL;
2658         }
2659         if (!AST_LIST_EMPTY(ast_channel_readq(peer))) {
2660                 ast_channel_unlock(peer);
2661                 return NULL;
2662         }
2663         if (ast_test_flag(ast_channel_flags(peer), AST_FLAG_EMULATE_DTMF)) {
2664                 ast_channel_unlock(peer);
2665                 return NULL;
2666         }
2667         if (ast_channel_has_audio_frame_or_monitor(peer)) {
2668                 /* Peer has an active monitor, audiohook, or framehook. */
2669                 ast_channel_unlock(peer);
2670                 return NULL;
2671         }
2672         bridge_channel = ast_channel_internal_bridge_channel(peer);
2673         if (!bridge_channel || ast_bridge_channel_trylock(bridge_channel)) {
2674                 ast_channel_unlock(peer);
2675                 return NULL;
2676         }
2677         bridge = bridge_channel->bridge;
2678         if (bridge_channel->activity != BRIDGE_CHANNEL_THREAD_IDLE
2679                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2680                 || ast_bridge_trylock(bridge)) {
2681                 ast_bridge_channel_unlock(bridge_channel);
2682                 ast_channel_unlock(peer);
2683                 return NULL;
2684         }
2685         if (!bridge_allows_optimization(bridge) ||
2686                         !bridge_channel_internal_allows_optimization(bridge_channel)) {
2687                 ast_bridge_unlock(bridge);
2688                 ast_bridge_channel_unlock(bridge_channel);
2689                 ast_channel_unlock(peer);
2690                 return NULL;
2691         }
2692         return bridge;
2693 }
2694
2695 /*!
2696  * \internal
2697  * \brief Indicates allowability of a swap optimization
2698  */
2699 enum bridge_allow_swap {
2700         /*! Bridges cannot allow for a swap optimization to occur */
2701         SWAP_PROHIBITED,
2702         /*! Bridge swap optimization can occur into the chan_bridge */
2703         SWAP_TO_CHAN_BRIDGE,
2704         /*! Bridge swap optimization can occur into the peer_bridge */
2705         SWAP_TO_PEER_BRIDGE,
2706 };
2707
2708 /*!
2709  * \internal
2710  * \brief Determine if two bridges allow for swap optimization to occur
2711  *
2712  * \param chan_bridge First bridge being tested
2713  * \param peer_bridge Second bridge being tested
2714  * \return Allowability of swap optimization
2715  */
2716 static enum bridge_allow_swap bridges_allow_swap_optimization(struct ast_bridge *chan_bridge,
2717                 struct ast_bridge *peer_bridge)
2718 {
2719         int chan_priority;
2720         int peer_priority;
2721
2722         if (!ast_test_flag(&chan_bridge->feature_flags,
2723                         AST_BRIDGE_FLAG_SWAP_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM |
2724                         AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2725                 && !ast_test_flag(&peer_bridge->feature_flags,
2726                         AST_BRIDGE_FLAG_SWAP_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM |
2727                         AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)) {
2728                 /*
2729                  * Can swap either way.  Swap to the higher priority merge
2730                  * bridge.
2731                  */
2732                 chan_priority = chan_bridge->v_table->get_merge_priority(chan_bridge);
2733                 peer_priority = peer_bridge->v_table->get_merge_priority(peer_bridge);
2734                 if (chan_bridge->num_channels == 2
2735                         && chan_priority <= peer_priority) {
2736                         return SWAP_TO_PEER_BRIDGE;
2737                 } else if (peer_bridge->num_channels == 2
2738                         && peer_priority <= chan_priority) {
2739                         return SWAP_TO_CHAN_BRIDGE;
2740                 }
2741         } else if (chan_bridge->num_channels == 2
2742                 && !ast_test_flag(&chan_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM | AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2743                 && !ast_test_flag(&peer_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_TO)) {
2744                 /* Can swap optimize only one way. */
2745                 return SWAP_TO_PEER_BRIDGE;
2746         } else if (peer_bridge->num_channels == 2
2747                 && !ast_test_flag(&peer_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM | AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2748                 && !ast_test_flag(&chan_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_TO)) {
2749                 /* Can swap optimize only one way. */
2750                 return SWAP_TO_CHAN_BRIDGE;
2751         }
2752
2753         return SWAP_PROHIBITED;
2754 }
2755
2756 /*!
2757  * \internal
2758  * \brief Check and attempt to swap optimize out the unreal channels.
2759  * \since 12.0.0
2760  *
2761  * \param chan_bridge
2762  * \param chan_bridge_channel
2763  * \param peer_bridge
2764  * \param peer_bridge_channel
2765  * \param pvt Unreal data containing callbacks to call if the optimization actually
2766  * happens
2767  *
2768  * \retval 1 if unreal channels failed to optimize out.
2769  * \retval 0 if unreal channels were not optimized out.
2770  * \retval -1 if unreal channels were optimized out.
2771  */
2772 static int try_swap_optimize_out(struct ast_bridge *chan_bridge,
2773         struct ast_bridge_channel *chan_bridge_channel, struct ast_bridge *peer_bridge,
2774         struct ast_bridge_channel *peer_bridge_channel,
2775         struct ast_unreal_pvt *pvt)
2776 {
2777         struct ast_bridge *dst_bridge;
2778         struct ast_bridge_channel *dst_bridge_channel;
2779         struct ast_bridge_channel *src_bridge_channel;
2780         struct ast_bridge_channel *other;
2781         int res = 1;
2782
2783         switch (bridges_allow_swap_optimization(chan_bridge, peer_bridge)) {
2784         case SWAP_TO_CHAN_BRIDGE:
2785                 dst_bridge = chan_bridge;
2786                 dst_bridge_channel = chan_bridge_channel;
2787                 src_bridge_channel = peer_bridge_channel;
2788                 break;
2789         case SWAP_TO_PEER_BRIDGE:
2790                 dst_bridge = peer_bridge;
2791                 dst_bridge_channel = peer_bridge_channel;
2792                 src_bridge_channel = chan_bridge_channel;
2793                 break;
2794         case SWAP_PROHIBITED:
2795         default:
2796                 return 0;
2797         }
2798
2799         other = ast_bridge_channel_peer(src_bridge_channel);
2800         if (other && other->state == BRIDGE_CHANNEL_STATE_WAIT) {
2801                 unsigned int id;
2802
2803                 if (ast_channel_trylock(other->chan)) {
2804                         return 1;
2805                 }
2806
2807                 id = ast_atomic_fetchadd_int((int *) &optimization_id, +1);
2808
2809                 ast_verb(4, "Move-swap optimizing %s <-- %s.\n",
2810                         ast_channel_name(dst_bridge_channel->chan),
2811                         ast_channel_name(other->chan));
2812
2813                 if (pvt && !ast_test_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN) && pvt->callbacks
2814                                 && pvt->callbacks->optimization_started) {
2815                         pvt->callbacks->optimization_started(pvt, other->chan,
2816                                         dst_bridge_channel->chan == pvt->owner ? AST_UNREAL_OWNER : AST_UNREAL_CHAN,
2817                                         id);
2818                         ast_set_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN);
2819                 }
2820                 other->swap = dst_bridge_channel->chan;
2821                 if (!bridge_do_move(dst_bridge, other, 1, 1)) {
2822                         ast_bridge_channel_leave_bridge(src_bridge_channel,
2823                                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
2824                         res = -1;
2825                 }
2826                 if (pvt && pvt->callbacks && pvt->callbacks->optimization_finished) {
2827                         pvt->callbacks->optimization_finished(pvt, res == 1, id);
2828                 }
2829                 ast_channel_unlock(other->chan);
2830         }
2831         return res;
2832 }
2833
2834 /*!
2835  * \internal
2836  * \brief Indicates allowability of a merge optimization
2837  */
2838 enum bridge_allow_merge {
2839         /*! Bridge properties prohibit merge optimization */
2840         MERGE_PROHIBITED,
2841         /*! Merge optimization cannot occur because the source bridge has too few channels */
2842         MERGE_NOT_ENOUGH_CHANNELS,
2843         /*! Merge optimization cannot occur because multimix capability could not be requested */
2844         MERGE_NO_MULTIMIX,
2845         /*! Merge optimization allowed between bridges */
2846         MERGE_ALLOWED,
2847 };
2848
2849 /*!
2850  * \internal
2851  * \brief Determines allowability of a merge optimization
2852  *
2853  * \note The merge output parameter is undefined if MERGE_PROHIBITED is returned. For success
2854  * and other failure returns, a merge direction was determined, and the parameter is safe to
2855  * access.
2856  *
2857  * \param chan_bridge First bridge being tested
2858  * \param peer_bridge Second bridge being tested
2859  * \param num_kick_channels The number of channels to remove from the bridges during merging
2860  * \param[out] merge Indicates the recommended direction for the bridge merge
2861  */
2862 static enum bridge_allow_merge bridges_allow_merge_optimization(struct ast_bridge *chan_bridge,
2863                 struct ast_bridge *peer_bridge, int num_kick_channels, struct merge_direction *merge)
2864 {
2865         *merge = bridge_merge_determine_direction(chan_bridge, peer_bridge);
2866         if (!merge->dest) {
2867                 return MERGE_PROHIBITED;
2868         }
2869         if (merge->src->num_channels < 2) {
2870                 return MERGE_NOT_ENOUGH_CHANNELS;
2871         } else if ((2 + num_kick_channels) < merge->dest->num_channels + merge->src->num_channels
2872                 && !(merge->dest->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)
2873                 && (!ast_test_flag(&merge->dest->feature_flags, AST_BRIDGE_FLAG_SMART)
2874                         || !(merge->dest->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX))) {
2875                 return MERGE_NO_MULTIMIX;
2876         }
2877
2878         return MERGE_ALLOWED;
2879 }
2880
2881 /*!
2882  * \internal
2883  * \brief Check and attempt to merge optimize out the unreal channels.
2884  * \since 12.0.0
2885  *
2886  * \param chan_bridge
2887  * \param chan_bridge_channel
2888  * \param peer_bridge
2889  * \param peer_bridge_channel
2890  * \param pvt Unreal data containing callbacks to call if the optimization actually
2891  * happens
2892  *
2893  * \retval 0 if unreal channels were not optimized out.
2894  * \retval -1 if unreal channels were optimized out.
2895  */
2896 static int try_merge_optimize_out(struct ast_bridge *chan_bridge,
2897         struct ast_bridge_channel *chan_bridge_channel, struct ast_bridge *peer_bridge,
2898         struct ast_bridge_channel *peer_bridge_channel,
2899         struct ast_unreal_pvt *pvt)
2900 {
2901         struct merge_direction merge;
2902         struct ast_bridge_channel *kick_me[] = {
2903                 chan_bridge_channel,
2904                 peer_bridge_channel,
2905         };
2906         unsigned int id;
2907
2908         switch (bridges_allow_merge_optimization(chan_bridge, peer_bridge, ARRAY_LEN(kick_me), &merge)) {
2909         case MERGE_ALLOWED:
2910                 break;
2911         case MERGE_PROHIBITED:
2912                 return 0;
2913         case MERGE_NOT_ENOUGH_CHANNELS:
2914                 ast_debug(4, "Can't optimize %s -- %s out, not enough channels in bridge %s.\n",
2915                         ast_channel_name(chan_bridge_channel->chan),
2916                         ast_channel_name(peer_bridge_channel->chan),
2917                         merge.src->uniqueid);
2918                 return 0;
2919         case MERGE_NO_MULTIMIX:
2920                 ast_debug(4, "Can't optimize %s -- %s out, multimix is needed and it cannot be acquired.\n",
2921                         ast_channel_name(chan_bridge_channel->chan),
2922                         ast_channel_name(peer_bridge_channel->chan));
2923                 return 0;
2924         }
2925
2926         ast_verb(4, "Merge optimizing %s -- %s out.\n",
2927                 ast_channel_name(chan_bridge_channel->chan),
2928                 ast_channel_name(peer_bridge_channel->chan));
2929
2930         id = ast_atomic_fetchadd_int((int *) &optimization_id, +1);
2931
2932         if (pvt && !ast_test_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN) && pvt->callbacks
2933                         && pvt->callbacks->optimization_started) {
2934                 pvt->callbacks->optimization_started(pvt, NULL,
2935                                 merge.dest == ast_channel_internal_bridge(pvt->owner) ? AST_UNREAL_OWNER : AST_UNREAL_CHAN,
2936                                 id);
2937                 ast_set_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN);
2938         }
2939         bridge_do_merge(merge.dest, merge.src, kick_me, ARRAY_LEN(kick_me), 1);
2940         if (pvt && pvt->callbacks && pvt->callbacks->optimization_finished) {
2941                 pvt->callbacks->optimization_finished(pvt, 1, id);
2942         }
2943
2944         return -1;
2945 }
2946
2947 int ast_bridge_unreal_optimize_out(struct ast_channel *chan, struct ast_channel *peer, struct ast_unreal_pvt *pvt)
2948 {
2949         struct ast_bridge *chan_bridge;
2950         struct ast_bridge *peer_bridge;
2951         struct ast_bridge_channel *chan_bridge_channel;
2952         struct ast_bridge_channel *peer_bridge_channel;
2953         int res = 0;
2954
2955         chan_bridge = optimize_lock_chan_stack(chan);
2956         if (!chan_bridge) {
2957                 return res;
2958         }
2959         chan_bridge_channel = ast_channel_internal_bridge_channel(chan);
2960
2961         peer_bridge = optimize_lock_peer_stack(peer);
2962         if (peer_bridge) {
2963                 peer_bridge_channel = ast_channel_internal_bridge_channel(peer);
2964
2965                 res = try_swap_optimize_out(chan_bridge, chan_bridge_channel,
2966                         peer_bridge, peer_bridge_channel, pvt);
2967                 if (!res) {
2968                         res = try_merge_optimize_out(chan_bridge, chan_bridge_channel,
2969                                 peer_bridge, peer_bridge_channel, pvt);
2970                 } else if (0 < res) {
2971                         res = 0;
2972                 }
2973
2974                 /* Release peer locks. */
2975                 ast_bridge_unlock(peer_bridge);
2976                 ast_bridge_channel_unlock(peer_bridge_channel);
2977                 ast_channel_unlock(peer);
2978         }
2979
2980         /* Release chan locks. */
2981         ast_bridge_unlock(chan_bridge);
2982         ast_bridge_channel_unlock(chan_bridge_channel);
2983
2984         return res;
2985 }
2986
2987 enum ast_bridge_optimization ast_bridges_allow_optimization(struct ast_bridge *chan_bridge,
2988                 struct ast_bridge *peer_bridge)
2989 {
2990         struct merge_direction merge;
2991
2992         if (!bridge_allows_optimization(chan_bridge) || !bridge_allows_optimization(peer_bridge)) {
2993                 return AST_BRIDGE_OPTIMIZE_PROHIBITED;
2994         }
2995
2996         switch (bridges_allow_swap_optimization(chan_bridge, peer_bridge)) {
2997         case SWAP_TO_CHAN_BRIDGE:
2998                 return AST_BRIDGE_OPTIMIZE_SWAP_TO_CHAN_BRIDGE;
2999         case SWAP_TO_PEER_BRIDGE:
3000                 return AST_BRIDGE_OPTIMIZE_SWAP_TO_PEER_BRIDGE;
3001         case SWAP_PROHIBITED:
3002         default:
3003                 break;
3004         }
3005
3006         /* Two channels will be kicked from the bridges, the unreal;1 and unreal;2 channels */
3007         if (bridges_allow_merge_optimization(chan_bridge, peer_bridge, 2, &merge) != MERGE_ALLOWED) {
3008                 return AST_BRIDGE_OPTIMIZE_PROHIBITED;
3009         }
3010
3011         if (merge.dest == chan_bridge) {
3012                 return AST_BRIDGE_OPTIMIZE_MERGE_TO_CHAN_BRIDGE;
3013         } else {
3014                 return AST_BRIDGE_OPTIMIZE_MERGE_TO_PEER_BRIDGE;
3015         }
3016 }
3017
3018 /*!
3019  * \internal
3020  * \brief Adjust the bridge merge inhibit request count.
3021  * \since 12.0.0
3022  *
3023  * \param bridge What to operate on.
3024  * \param request Inhibit request increment.
3025  *     (Positive to add requests.  Negative to remove requests.)
3026  *
3027  * \note This function assumes bridge is locked.
3028  *
3029  * \return Nothing
3030  */
3031 void bridge_merge_inhibit_nolock(struct ast_bridge *bridge, int request)
3032 {
3033         int new_request;
3034
3035         new_request = bridge->inhibit_merge + request;
3036         ast_assert(0 <= new_request);
3037         bridge->inhibit_merge = new_request;
3038 }
3039
3040 void ast_bridge_merge_inhibit(struct ast_bridge *bridge, int request)
3041 {
3042         ast_bridge_lock(bridge);
3043         bridge_merge_inhibit_nolock(bridge, request);
3044         ast_bridge_unlock(bridge);
3045 }
3046
3047 int ast_bridge_suspend(struct ast_bridge *bridge, struct ast_channel *chan)
3048 {
3049         struct ast_bridge_channel *bridge_channel;
3050 /* XXX ASTERISK-21271 the case of a disolved bridge while channel is suspended is not handled. */
3051 /* XXX ASTERISK-21271 suspend/unsuspend needs to be rethought. The caller must block until it has successfully suspended the channel for temporary control. */
3052 /* XXX ASTERISK-21271 external suspend/unsuspend needs to be eliminated. The channel may be playing a file at the time and stealing it then is not good. */
3053
3054         ast_bridge_lock(bridge);
3055
3056         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
3057                 ast_bridge_unlock(bridge);
3058                 return -1;
3059         }
3060
3061         bridge_channel_internal_suspend_nolock(bridge_channel);
3062
3063         ast_bridge_unlock(bridge);
3064
3065         return 0;
3066 }
3067
3068 int ast_bridge_unsuspend(struct ast_bridge *bridge, struct ast_channel *chan)
3069 {
3070         struct ast_bridge_channel *bridge_channel;
3071 /* XXX ASTERISK-21271 the case of a disolved bridge while channel is suspended is not handled. */
3072
3073         ast_bridge_lock(bridge);
3074
3075         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
3076                 ast_bridge_unlock(bridge);
3077                 return -1;
3078         }
3079
3080         bridge_channel_internal_unsuspend_nolock(bridge_channel);
3081
3082         ast_bridge_unlock(bridge);
3083
3084         return 0;
3085 }
3086
3087 void ast_bridge_technology_suspend(struct ast_bridge_technology *technology)
3088 {
3089         technology->suspended = 1;
3090 }
3091
3092 void ast_bridge_technology_unsuspend(struct ast_bridge_technology *technology)
3093 {
3094         /*
3095          * XXX We may want the act of unsuspending a bridge technology
3096          * to prod all existing bridges to see if they should start
3097          * using it.
3098          */
3099         technology->suspended = 0;
3100 }
3101
3102 int ast_bridge_features_register(enum ast_bridge_builtin_feature feature, ast_bridge_hook_callback callback, const char *dtmf)
3103 {
3104         if (ARRAY_LEN(builtin_features_handlers) <= feature
3105                 || builtin_features_handlers[feature]) {
3106                 return -1;
3107         }
3108
3109         if (!ast_strlen_zero(dtmf)) {
3110                 ast_copy_string(builtin_features_dtmf[feature], dtmf, sizeof(builtin_features_dtmf[feature]));
3111         }
3112
3113         builtin_features_handlers[feature] = callback;
3114
3115         return 0;
3116 }
3117
3118 int ast_bridge_features_unregister(enum ast_bridge_builtin_feature feature)
3119 {
3120         if (ARRAY_LEN(builtin_features_handlers) <= feature
3121                 || !builtin_features_handlers[feature]) {
3122                 return -1;
3123         }
3124
3125         builtin_features_handlers[feature] = NULL;
3126
3127         return 0;
3128 }
3129
3130 int ast_bridge_features_do(enum ast_bridge_builtin_feature feature, struct ast_bridge_channel *bridge_channel, void *hook_pvt)
3131 {
3132         ast_bridge_hook_callback callback;
3133
3134         if (ARRAY_LEN(builtin_features_handlers) <= feature) {
3135                 return -1;
3136         }
3137
3138         callback = builtin_features_handlers[feature];
3139         if (!callback) {
3140                 return -1;
3141         }
3142         callback(bridge_channel, hook_pvt);
3143
3144         return 0;
3145 }
3146
3147 int ast_bridge_interval_register(enum ast_bridge_builtin_interval interval, ast_bridge_builtin_set_limits_fn callback)
3148 {
3149         if (ARRAY_LEN(builtin_interval_handlers) <= interval
3150                 || builtin_interval_handlers[interval]) {
3151                 return -1;
3152         }
3153
3154         builtin_interval_handlers[interval] = callback;
3155
3156         return 0;
3157 }
3158
3159 int ast_bridge_interval_unregister(enum ast_bridge_builtin_interval interval)
3160 {
3161         if (ARRAY_LEN(builtin_interval_handlers) <= interval
3162                 || !builtin_interval_handlers[interval]) {
3163                 return -1;
3164         }
3165
3166         builtin_interval_handlers[interval] = NULL;
3167
3168         return 0;
3169
3170 }
3171
3172 /*!
3173  * \internal
3174  * \brief Bridge hook destructor.
3175  * \since 12.0.0
3176  *
3177  * \param vhook Object to destroy.
3178  *
3179  * \return Nothing
3180  */
3181 static void bridge_hook_destroy(void *vhook)
3182 {
3183         struct ast_bridge_hook *hook = vhook;
3184
3185         if (hook->destructor) {
3186                 hook->destructor(hook->hook_pvt);
3187         }
3188 }
3189
3190 /*!
3191  * \internal
3192  * \brief Allocate and setup a generic bridge hook.
3193  * \since 12.0.0
3194  *
3195  * \param size How big an object to allocate.
3196  * \param callback Function to execute upon activation
3197  * \param hook_pvt Unique data
3198  * \param destructor Optional destructor callback for hook_pvt data
3199  * \param remove_flags Dictates what situations the hook should be removed.
3200  *
3201  * \retval hook on success.
3202  * \retval NULL on error.
3203  */
3204 static struct ast_bridge_hook *bridge_hook_generic(size_t size,
3205         ast_bridge_hook_callback callback,
3206         void *hook_pvt,
3207         ast_bridge_hook_pvt_destructor destructor,
3208         enum ast_bridge_hook_remove_flags remove_flags)
3209 {
3210         struct ast_bridge_hook *hook;
3211
3212         /* Allocate new hook and setup it's basic variables */
3213         hook = ao2_alloc_options(size, bridge_hook_destroy, AO2_ALLOC_OPT_LOCK_NOLOCK);
3214         if (hook) {
3215                 hook->callback = callback;
3216                 hook->destructor = destructor;
3217                 hook->hook_pvt = hook_pvt;
3218                 ast_set_flag(&hook->remove_flags, remove_flags);
3219         }
3220
3221         return hook;
3222 }
3223
3224 int ast_bridge_dtmf_hook(struct ast_bridge_features *features,
3225         const char *dtmf,
3226         ast_bridge_hook_callback callback,
3227         void *hook_pvt,
3228         ast_bridge_hook_pvt_destructor destructor,
3229         enum ast_bridge_hook_remove_flags remove_flags)
3230 {
3231         struct ast_bridge_hook_dtmf *hook;
3232         int res;
3233
3234         /* Allocate new hook and setup it's various variables */
3235         hook = (struct ast_bridge_hook_dtmf *) bridge_hook_generic(sizeof(*hook), callback,
3236                 hook_pvt, destructor, remove_flags);
3237         if (!hook) {
3238                 return -1;
3239         }
3240         hook->generic.type = AST_BRIDGE_HOOK_TYPE_DTMF;
3241         ast_copy_string(hook->dtmf.code, dtmf, sizeof(hook->dtmf.code));
3242
3243         /* Once done we put it in the container. */
3244         res = ao2_link(features->dtmf_hooks, hook) ? 0 : -1;
3245         if (res) {
3246                 /*
3247                  * Could not link the hook into the container.
3248                  *
3249                  * Remove the hook_pvt destructor call from the hook since we
3250                  * are returning failure to install the hook.
3251                  */
3252                 hook->generic.destructor = NULL;
3253         }
3254         ao2_ref(hook, -1);
3255
3256         return res;
3257 }
3258
3259 /*!
3260  * \internal
3261  * \brief Attach an other hook to a bridge features structure
3262  *
3263  * \param features Bridge features structure
3264  * \param callback Function to execute upon activation
3265  * \param hook_pvt Unique data
3266  * \param destructor Optional destructor callback for hook_pvt data
3267  * \param remove_flags Dictates what situations the hook should be removed.
3268  * \param type What type of hook is being attached.
3269  *
3270  * \retval 0 on success
3271  * \retval -1 on failure (The caller must cleanup any hook_pvt resources.)
3272  */
3273 static int bridge_other_hook(struct ast_bridge_features *features,
3274         ast_bridge_hook_callback callback,
3275         void *hook_pvt,
3276         ast_bridge_hook_pvt_destructor destructor,
3277         enum ast_bridge_hook_remove_flags remove_flags,
3278         enum ast_bridge_hook_type type)
3279 {
3280         struct ast_bridge_hook *hook;
3281         int res;
3282
3283         /* Allocate new hook and setup it's various variables */
3284         hook = bridge_hook_generic(sizeof(*hook), callback, hook_pvt, destructor,
3285                 remove_flags);
3286         if (!hook) {
3287                 return -1;
3288         }
3289         hook->type = type;
3290
3291         /* Once done we put it in the container. */
3292         res = ao2_link(features->other_hooks, hook) ? 0 : -1;
3293         if (res) {
3294                 /*
3295                  * Could not link the hook into the container.
3296                  *
3297                  * Remove the hook_pvt destructor call from the hook since we
3298                  * are returning failure to install the hook.
3299                  */
3300                 hook->destructor = NULL;
3301         }
3302         ao2_ref(hook, -1);
3303
3304         return res;
3305 }
3306
3307 int ast_bridge_hangup_hook(struct ast_bridge_features *features,
3308         ast_bridge_hook_callback callback,
3309         void *hook_pvt,
3310         ast_bridge_hook_pvt_destructor destructor,
3311         enum ast_bridge_hook_remove_flags remove_flags)
3312 {
3313         return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
3314                 AST_BRIDGE_HOOK_TYPE_HANGUP);
3315 }
3316
3317 int ast_bridge_join_hook(struct ast_bridge_features *features,
3318         ast_bridge_hook_callback callback,
3319         void *hook_pvt,
3320         ast_bridge_hook_pvt_destructor destructor,
3321         enum ast_bridge_hook_remove_flags remove_flags)
3322 {
3323         return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
3324                 AST_BRIDGE_HOOK_TYPE_JOIN);
3325 }
3326
3327 int ast_bridge_leave_hook(struct ast_bridge_features *features,
3328         ast_bridge_hook_callback callback,
3329         void *hook_pvt,
3330         ast_bridge_hook_pvt_destructor destructor,
3331         enum ast_bridge_hook_remove_flags remove_flags)
3332 {
3333         return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
3334                 AST_BRIDGE_HOOK_TYPE_LEAVE);
3335 }
3336
3337 int ast_bridge_talk_detector_hook(struct ast_bridge_features *features,
3338         ast_bridge_talking_indicate_callback callback,
3339         void *hook_pvt,
3340         ast_bridge_hook_pvt_destructor destructor,
3341         enum ast_bridge_hook_remove_flags remove_flags)
3342 {
3343         ast_bridge_hook_callback hook_cb = (ast_bridge_hook_callback) callback;
3344
3345         return bridge_other_hook(features, hook_cb, hook_pvt, destructor, remove_flags,
3346                 AST_BRIDGE_HOOK_TYPE_TALK);
3347 }
3348
3349 int ast_bridge_move_hook(struct ast_bridge_features *features,
3350         ast_bridge_move_indicate_callback callback,
3351         void *hook_pvt,
3352         ast_bridge_hook_pvt_destructor destructor,
3353         enum ast_bridge_hook_remove_flags remove_flags)
3354 {
3355         ast_bridge_hook_callback hook_cb = (ast_bridge_hook_callback) callback;
3356
3357         return bridge_other_hook(features, hook_cb, hook_pvt, destructor, remove_flags,
3358                 AST_BRIDGE_HOOK_TYPE_MOVE);
3359 }
3360
3361 int ast_bridge_interval_hook(struct ast_bridge_features *features,
3362         enum ast_bridge_hook_timer_option flags,
3363         unsigned int interval,
3364         ast_bridge_hook_callback callback,
3365         void *hook_pvt,
3366         ast_bridge_hook_pvt_destructor destructor,
3367         enum ast_bridge_hook_remove_flags remove_flags)
3368 {
3369         struct ast_bridge_hook_timer *hook;
3370         int res;
3371
3372         if (!features ||!interval || !callback) {
3373                 return -1;
3374         }
3375
3376         /* Allocate new hook and setup it's various variables */
3377         hook = (struct ast_bridge_hook_timer *) bridge_hook_generic(sizeof(*hook), callback,
3378                 hook_pvt, destructor, remove_flags);
3379         if (!hook) {
3380                 return -1;
3381         }
3382         hook->generic.type = AST_BRIDGE_HOOK_TYPE_TIMER;
3383         hook->timer.interval = interval;
3384         hook->timer.trip_time = ast_tvadd(ast_tvnow(), ast_samp2tv(interval, 1000));
3385         hook->timer.seqno = ast_atomic_fetchadd_int((int *) &features->interval_sequence, +1);
3386         hook->timer.flags = flags;
3387
3388         ast_debug(1, "Putting interval hook %p with interval %u in the heap on features %p\n",
3389                 hook, hook->timer.interval, features);
3390         ast_heap_wrlock(features->interval_hooks);
3391         res = ast_heap_push(features->interval_hooks, hook);
3392         ast_heap_unlock(features->interval_hooks);
3393         if (res) {
3394                 /*
3395                  * Could not push the hook into the heap
3396                  *
3397                  * Remove the hook_pvt destructor call from the hook since we
3398                  * are returning failure to install the hook.
3399                  */
3400                 hook->generic.destructor = NULL;
3401                 ao2_ref(hook, -1);
3402         }
3403
3404         return res ? -1 : 0;
3405 }
3406
3407 int ast_bridge_features_enable(struct ast_bridge_features *features,
3408         enum ast_bridge_builtin_feature feature,
3409         const char *dtmf,
3410         void *config,
3411         ast_bridge_hook_pvt_destructor destructor,
3412         enum ast_bridge_hook_remove_flags remove_flags)
3413 {
3414         if (ARRAY_LEN(builtin_features_handlers) <= feature
3415                 || !builtin_features_handlers[feature]) {
3416                 return -1;
3417         }
3418
3419         /* If no alternate DTMF stream was provided use the default one */
3420         if (ast_strlen_zero(dtmf)) {
3421                 dtmf = builtin_features_dtmf[feature];
3422                 /* If no DTMF is still available (ie: it has been disabled) then error out now */
3423                 if (ast_strlen_zero(dtmf)) {
3424                         ast_debug(1, "Failed to enable built in feature %u on %p, no DTMF string is available for it.\n",
3425                                 feature, features);
3426                         return -1;
3427                 }
3428         }
3429
3430         /*
3431          * The rest is basically pretty easy.  We create another hook
3432          * using the built in feature's DTMF callback.  Easy as pie.
3433          */
3434         return ast_bridge_dtmf_hook(features, dtmf, builtin_features_handlers[feature],
3435                 config, destructor, remove_flags);
3436 }
3437
3438 int ast_bridge_features_limits_construct(struct ast_bridge_features_limits *limits)
3439 {
3440         memset(limits, 0, sizeof(*limits));
3441
3442         if (ast_string_field_init(limits, 256)) {
3443                 return -1;
3444         }
3445
3446         return 0;
3447 }
3448
3449 void ast_bridge_features_limits_destroy(struct ast_bridge_features_limits *limits)
3450 {
3451         ast_string_field_free_memory(limits);
3452 }
3453
3454 int ast_bridge_features_set_limits(struct ast_bridge_features *features,
3455         struct ast_bridge_features_limits *limits,
3456         enum ast_bridge_hook_remove_flags remove_flags)
3457 {
3458         if (builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_LIMITS]) {
3459                 ast_bridge_builtin_set_limits_fn callback;
3460
3461                 callback = builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_LIMITS];
3462                 return callback(features, limits, remove_flags);
3463         }
3464
3465         ast_log(LOG_ERROR, "Attempted to set limits without an AST_BRIDGE_BUILTIN_INTERVAL_LIMITS callback registered.\n");
3466         return -1;
3467 }
3468
3469 void ast_bridge_features_set_flag(struct ast_bridge_features *features, unsigned int flag)
3470 {
3471         ast_set_flag(&features->feature_flags, flag);
3472         features->usable = 1;
3473 }
3474
3475 /*!
3476  * \internal
3477  * \brief ao2 object match hooks with appropriate remove_flags.
3478  * \since 12.0.0
3479  *
3480  * \param obj Feature hook object.
3481  * \param arg Removal flags
3482  * \param flags Not used
3483  *
3484  * \retval CMP_MATCH if hook's remove_flags match the removal flags set.
3485  * \retval 0 if not match.
3486  */
3487 static int hook_remove_match(void *obj, void *arg, int flags)
3488 {
3489         struct ast_bridge_hook *hook = obj;
3490         enum ast_bridge_hook_remove_flags *remove_flags = arg;
3491
3492         if (ast_test_flag(&hook->remove_flags, *remove_flags)) {
3493                 return CMP_MATCH;
3494         } else {
3495                 return 0;
3496         }
3497 }
3498
3499 /*!
3500  * \internal
3501  * \brief Remove all hooks with appropriate remove_flags in the container.
3502  * \since 12.0.0
3503  *
3504  * \param hooks Hooks container to work on.
3505  * \param remove_flags Determinator for whether hook is removed
3506  *
3507  * \return Nothing
3508  */
3509 static void hooks_remove_container(struct ao2_container *hooks, enum ast_bridge_hook_remove_flags remove_flags)
3510 {
3511         ao2_callback(hooks, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
3512                 hook_remove_match, &remove_flags);
3513 }
3514
3515 /*!
3516  * \internal
3517  * \brief Remove all hooks in the heap with appropriate remove_flags set.
3518  * \since 12.0.0
3519  *
3520  * \param hooks Hooks heap to work on.
3521  * \param remove_flags Determinator for whether hook is removed
3522  *
3523  * \return Nothing
3524  */
3525 static void hooks_remove_heap(struct ast_heap *hooks, enum ast_bridge_hook_remove_flags remove_flags)
3526 {
3527         struct ast_bridge_hook *hook;
3528         int changed;
3529
3530         ast_heap_wrlock(hooks);
3531         do {
3532                 int idx;
3533
3534                 changed = 0;
3535                 for (idx = ast_heap_size(hooks); idx; --idx) {
3536                         hook = ast_heap_peek(hooks, idx);
3537                         if (ast_test_flag(&hook->remove_flags, remove_flags)) {
3538                                 ast_heap_remove(hooks, hook);
3539                                 ao2_ref(hook, -1);
3540                                 changed = 1;
3541                         }
3542                 }
3543         } while (changed);
3544         ast_heap_unlock(hooks);
3545 }
3546
3547 void ast_bridge_features_remove(struct ast_bridge_features *features, enum ast_bridge_hook_remove_flags remove_flags)
3548 {
3549         hooks_remove_container(features->dtmf_hooks, remove_flags);
3550         hooks_remove_container(features->other_hooks, remove_flags);
3551         hooks_remove_heap(features->interval_hooks, remove_flags);
3552 }
3553
3554 static int interval_hook_time_cmp(void *a, void *b)
3555 {
3556         struct ast_bridge_hook_timer *hook_a = a;
3557         struct ast_bridge_hook_timer *hook_b = b;
3558         int cmp;
3559
3560         cmp = ast_tvcmp(hook_b->timer.trip_time, hook_a->timer.trip_time);
3561         if (cmp) {
3562                 return cmp;
3563         }
3564
3565         cmp = hook_b->timer.seqno - hook_a->timer.seqno;
3566         return cmp;
3567 }
3568
3569 /*!
3570  * \internal
3571  * \brief DTMF hook container sort comparison function.
3572  * \since 12.0.0
3573  *
3574  * \param obj_left pointer to the (user-defined part) of an object.
3575  * \param obj_right pointer to the (user-defined part) of an object.
3576  * \param flags flags from ao2_callback()
3577  *   OBJ_POINTER - if set, 'obj_right', is an object.
3578  *   OBJ_KEY - if set, 'obj_right', is a search key item that is not an object.
3579  *   OBJ_PARTIAL_KEY - if set, 'obj_right', is a partial search key item that is not an object.
3580  *
3581  * \retval <0 if obj_left < obj_right
3582  * \retval =0 if obj_left == obj_right
3583  * \retval >0 if obj_left > obj_right
3584  */
3585 static int bridge_dtmf_hook_sort(const void *obj_left, const void *obj_right, int flags)
3586 {
3587         const struct ast_bridge_hook_dtmf *hook_left = obj_left;
3588         const struct ast_bridge_hook_dtmf *hook_right = obj_right;
3589         const char *right_key = obj_right;
3590         int cmp;
3591
3592         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
3593         default:
3594         case OBJ_POINTER:
3595                 right_key = hook_right->dtmf.code;
3596                 /* Fall through */
3597         case OBJ_KEY:
3598                 cmp = strcasecmp(hook_left->dtmf.code, right_key);
3599                 break;
3600         case OBJ_PARTIAL_KEY:
3601                 cmp = strncasecmp(hook_left->dtmf.code, right_key, strlen(right_key));
3602                 break;
3603         }
3604         return cmp;
3605 }
3606
3607 /*! \brief Callback for merging hook ao2_containers */
3608 static int merge_container_cb(void *obj, void *data, int flags)
3609 {
3610         ao2_link(data, obj);
3611         return 0;
3612 }
3613
3614 /*! \brief Wrapper for interval hooks that calls into the wrapped hook */
3615 static int interval_wrapper_cb(struct ast_bridge_channel *bridge_channel, void *obj)
3616 {
3617         struct ast_bridge_hook_timer *hook = obj;
3618
3619         return hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
3620 }
3621
3622 /*! \brief Destructor for the hook wrapper */
3623 static void interval_wrapper_pvt_dtor(void *obj)
3624 {
3625         ao2_cleanup(obj);
3626 }
3627
3628 /*! \brief Wrap the provided interval hook and add it to features */
3629 static void wrap_hook(struct ast_bridge_features *features, struct ast_bridge_hook_timer *hook)
3630 {
3631         /* Break out of the current wrapper if it exists to avoid multiple layers */
3632         if (hook->generic.callback == interval_wrapper_cb) {
3633                 hook = hook->generic.hook_pvt;
3634         }
3635
3636         ast_bridge_interval_hook(features, hook->timer.flags, hook->timer.interval,
3637                 interval_wrapper_cb, ao2_bump(hook), interval_wrapper_pvt_dtor,
3638                 hook->generic.remove_flags.flags);
3639 }
3640
3641 void ast_bridge_features_merge(struct ast_bridge_features *into, const struct ast_bridge_features *from)
3642 {
3643         struct ast_bridge_hook_timer *hook;
3644         int idx;
3645
3646         /* Merge hook containers */
3647         ao2_callback(from->dtmf_hooks, 0, merge_container_cb, into->dtmf_hooks);
3648         ao2_callback(from->other_hooks, 0, merge_container_cb, into->other_hooks);
3649
3650         /* Merge hook heaps */
3651         ast_heap_wrlock(from->interval_hooks);
3652         for (idx = 1; (hook = ast_heap_peek(from->interval_hooks, idx)); idx++) {
3653                 wrap_hook(into, hook);
3654         }
3655         ast_heap_unlock(from->interval_hooks);
3656
3657         /* Merge feature flags */
3658         into->feature_flags.flags |= from->feature_flags.flags;
3659         into->usable |= from->usable;
3660
3661         into->mute |= from->mute;
3662         into->dtmf_passthrough |= from->dtmf_passthrough;
3663 }
3664
3665 /* XXX ASTERISK-21271 make ast_bridge_features_init() static when make ast_bridge_join() requires features to be allocated. */
3666 int ast_bridge_features_init(struct ast_bridge_features *features)
3667 {
3668         /* Zero out the structure */
3669         memset(features, 0, sizeof(*features));
3670
3671         /* Initialize the DTMF hooks container */
3672         features->dtmf_hooks = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX,
3673                 AO2_CONTAINER_ALLOC_OPT_DUPS_REPLACE, bridge_dtmf_hook_sort, NULL);
3674         if (!features->dtmf_hooks) {
3675                 return -1;
3676         }
3677
3678         /* Initialize the miscellaneous other hooks container */
3679         features->other_hooks = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL,
3680                 NULL);
3681         if (!features->other_hooks) {
3682                 return -1;
3683         }
3684
3685         /* Initialize the interval hooks heap */
3686         features->interval_hooks = ast_heap_create(8, interval_hook_time_cmp,
3687                 offsetof(struct ast_bridge_hook_timer, timer.heap_index));
3688         if (!features->interval_hooks) {
3689                 return -1;
3690         }
3691
3692         features->dtmf_passthrough = 1;
3693
3694         return 0;
3695 }
3696
3697 /* XXX ASTERISK-21271 make ast_bridge_features_cleanup() static when make ast_bridge_join() requires features to be allocated. */
3698 void ast_bridge_features_cleanup(struct ast_bridge_features *features)
3699 {
3700         struct ast_bridge_hook_timer *hook;
3701
3702         /* Destroy the interval hooks heap. */
3703         if (features->interval_hooks) {
3704                 while ((hook = ast_heap_pop(features->interval_hooks))) {
3705                         ao2_ref(hook, -1);
3706                 }
3707                 features->interval_hooks = ast_heap_destroy(features->interval_hooks);
3708         }
3709
3710         /* Destroy the miscellaneous other hooks container. */
3711         ao2_cleanup(features->other_hooks);
3712         features->other_hooks = NULL;
3713
3714         /* Destroy the DTMF hooks container. */
3715         ao2_cleanup(features->dtmf_hooks);
3716         features->dtmf_hooks = NULL;
3717 }
3718
3719 void ast_bridge_features_destroy(struct ast_bridge_features *features)
3720 {
3721         if (!features) {
3722                 return;
3723         }
3724         ast_bridge_features_cleanup(features);
3725         ast_free(features);
3726 }
3727
3728 struct ast_bridge_features *ast_bridge_features_new(void)
3729 {
3730         struct ast_bridge_features *features;
3731
3732         features = ast_malloc(sizeof(*features));
3733         if (features) {
3734                 if (ast_bridge_features_init(features)) {
3735                         ast_bridge_features_destroy(features);
3736                         features = NULL;
3737                 }
3738         }
3739
3740         return features;
3741 }
3742
3743 void ast_bridge_set_mixing_interval(struct ast_bridge *bridge, unsigned int mixing_interval)
3744 {
3745         ast_bridge_lock(bridge);
3746         bridge->softmix.internal_mixing_interval = mixing_interval;
3747         ast_bridge_unlock(bridge);
3748 }
3749
3750 void ast_bridge_set_binaural_active(struct ast_bridge *bridge, unsigned int binaural_active)
3751 {
3752         ast_bridge_lock(bridge);
3753         bridge->softmix.binaural_active = binaural_active;
3754         ast_bridge_unlock(bridge);
3755 }
3756
3757 void ast_bridge_set_internal_sample_rate(struct ast_bridge *bridge, unsigned int sample_rate)
3758 {
3759         ast_bridge_lock(bridge);
3760         bridge->softmix.internal_sample_rate = sample_rate;
3761         ast_bridge_unlock(bridge);
3762 }
3763
3764 static void cleanup_video_mode(struct ast_bridge *bridge)
3765 {
3766         switch (bridge->softmix.video_mode.mode) {
3767         case AST_BRIDGE_VIDEO_MODE_NONE:
3768                 break;
3769         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3770                 if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc) {
3771                         ast_channel_unref(bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc);
3772                 }
3773                 break;
3774         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3775                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc) {
3776                         ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc);
3777                 }
3778                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc) {
3779                         ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc);
3780                 }
3781         case AST_BRIDGE_VIDEO_MODE_SFU:
3782                 break;
3783         }
3784         memset(&bridge->softmix.video_mode, 0, sizeof(bridge->softmix.video_mode));
3785 }
3786
3787 void ast_bridge_set_single_src_video_mode(struct ast_bridge *bridge, struct ast_channel *video_src_chan)
3788 {
3789         ast_bridge_lock(bridge);
3790         cleanup_video_mode(bridge);
3791         bridge->softmix.video_mode.mode = AST_BRIDGE_VIDEO_MODE_SINGLE_SRC;
3792         bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc = ast_channel_ref(video_src_chan);
3793         ast_verb(5, "Video source in bridge '%s' (%s) is now '%s' (%s)\n",
3794                 bridge->name, bridge->uniqueid,
3795                 ast_channel_name(video_src_chan),
3796                 ast_channel_uniqueid(video_src_chan));
3797         ast_bridge_publish_state(bridge);
3798         ast_indicate(video_src_chan, AST_CONTROL_VIDUPDATE);
3799         ast_bridge_unlock(bridge);
3800 }
3801
3802 void ast_bridge_set_talker_src_video_mode(struct ast_bridge *bridge)
3803 {
3804         ast_bridge_lock(bridge);
3805         cleanup_video_mode(bridge);
3806         bridge->softmix.video_mode.mode = AST_BRIDGE_VIDEO_MODE_TALKER_SRC;
3807         ast_bridge_unlock(bridge);
3808 }
3809
3810 void ast_bridge_set_sfu_video_mode(struct ast_bridge *bridge)
3811 {
3812         ast_bridge_lock(bridge);
3813         cleanup_video_mode(bridge);
3814         bridge->softmix.video_mode.mode = AST_BRIDGE_VIDEO_MODE_SFU;
3815         ast_bridge_unlock(bridge);
3816 }
3817
3818 void ast_bridge_update_talker_src_video_mode(struct ast_bridge *bridge, struct ast_channel *chan, int talker_energy, int is_keyframe)
3819 {
3820         struct ast_bridge_video_talker_src_data *data;
3821
3822         /* If the channel doesn't support video, we don't care about it */
3823         if (!ast_format_cap_has_type(ast_channel_nativeformats(chan), AST_MEDIA_TYPE_VIDEO)) {
3824                 return;
3825         }
3826
3827         ast_bridge_lock(bridge);
3828         data = &bridge->softmix.video_mode.mode_data.talker_src_data;
3829
3830         if (data->chan_vsrc == chan) {
3831                 data->average_talking_energy = talker_energy;
3832         } else if ((data->average_talking_energy < talker_energy) && is_keyframe) {
3833                 if (data->chan_old_vsrc) {
3834                         ast_channel_unref(data->chan_old_vsrc);
3835                 }
3836                 if (data->chan_vsrc) {
3837                         data->chan_old_vsrc = data->chan_vsrc;
3838                         ast_indicate(data->chan_old_vsrc, AST_CONTROL_VIDUPDATE);
3839                 }
3840                 data->chan_vsrc = ast_channel_ref(chan);
3841                 data->average_talking_energy = talker_energy;
3842                 ast_verb(5, "Video source in bridge '%s' (%s) is now '%s' (%s)\n",
3843                         bridge->name, bridge->uniqueid,
3844                         ast_channel_name(data->chan_vsrc),
3845                         ast_channel_uniqueid(data->chan_vsrc));
3846                 ast_bridge_publish_state(bridge);
3847                 ast_indicate(data->chan_vsrc, AST_CONTROL_VIDUPDATE);
3848         } else if ((data->average_talking_energy < talker_energy) && !is_keyframe) {
3849                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
3850         } else if (!data->chan_vsrc && is_keyframe) {
3851                 data->chan_vsrc = ast_channel_ref(chan);
3852                 data->average_talking_energy = talker_energy;
3853                 ast_verb(5, "Video source in bridge '%s' (%s) is now '%s' (%s)\n",
3854                         bridge->name, bridge->uniqueid,
3855                         ast_channel_name(data->chan_vsrc),
3856                         ast_channel_uniqueid(data->chan_vsrc));
3857                 ast_bridge_publish_state(bridge);
3858                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
3859         } else if (!data->chan_old_vsrc && is_keyframe) {
3860                 data->chan_old_vsrc = ast_channel_ref(chan);
3861                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
3862         }
3863         ast_bridge_unlock(bridge);
3864 }
3865
3866 int ast_bridge_number_video_src(struct ast_bridge *bridge)
3867 {
3868         int res = 0;
3869
3870         ast_bridge_lock(bridge);
3871         switch (bridge->softmix.video_mode.mode) {
3872         case AST_BRIDGE_VIDEO_MODE_NONE:
3873                 break;
3874         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3875                 if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc) {
3876                         res = 1;
3877                 }
3878                 break;
3879         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3880                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc) {
3881                         res++;
3882                 }
3883                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc) {
3884                         res++;
3885                 }
3886         case AST_BRIDGE_VIDEO_MODE_SFU:
3887                 break;
3888         }
3889         ast_bridge_unlock(bridge);
3890         return res;
3891 }
3892
3893 int ast_bridge_is_video_src(struct ast_bridge *bridge, struct ast_channel *chan)
3894 {
3895         int res = 0;
3896
3897         ast_bridge_lock(bridge);
3898         switch (bridge->softmix.video_mode.mode) {
3899         case AST_BRIDGE_VIDEO_MODE_NONE:
3900                 break;
3901         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3902                 if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc == chan) {
3903                         res = 1;
3904                 }
3905                 break;
3906         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3907                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc == chan) {
3908                         res = 1;
3909                 } else if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc == chan) {
3910                         res = 2;
3911                 }
3912         case AST_BRIDGE_VIDEO_MODE_SFU:
3913                 break;
3914         }
3915         ast_bridge_unlock(bridge);
3916         return res;
3917 }
3918
3919 void ast_bridge_remove_video_src(struct ast_bridge *bridge, struct ast_channel *chan)
3920 {
3921         ast_bridge_lock(bridge);
3922         switch (bridge->softmix.video_mode.mode) {
3923         case AST_BRIDGE_VIDEO_MODE_NONE:
3924                 break;
3925         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3926                 if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc == chan) {
3927                         if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc) {
3928                                 ast_channel_unref(bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc);
3929                         }
3930                         bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc = NULL;
3931                 }
3932                 break;
3933         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3934                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc == chan) {
3935                         if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc) {
3936                                 ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc);
3937                         }
3938                         bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc = NULL;
3939                         bridge->softmix.video_mode.mode_data.talker_src_data.average_talking_energy = 0;
3940                 }
3941                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc == chan) {
3942                         if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc) {
3943                                 ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc);
3944                         }
3945                         bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc = NULL;
3946                 }
3947         case AST_BRIDGE_VIDEO_MODE_SFU:
3948                 break;
3949         }
3950         ast_bridge_unlock(bridge);
3951 }
3952
3953 const char *ast_bridge_video_mode_to_string(enum ast_bridge_video_mode_type video_mode)
3954 {
3955         switch (video_mode) {
3956         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3957                 return "talker";
3958         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3959                 return "single";
3960         case AST_BRIDGE_VIDEO_MODE_SFU:
3961                 return "sfu";
3962         case AST_BRIDGE_VIDEO_MODE_NONE:
3963         default:
3964                 return "none";
3965         }
3966 }
3967
3968 static int channel_hash(const void *obj, int flags)
3969 {
3970         const struct ast_channel *chan = obj;
3971         const char *name = obj;
3972         int hash;
3973
3974         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
3975         default:
3976         case OBJ_POINTER: