bridge: Old channel video source not set to NULL after unref.
[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         if (bridge_channel->bridge->technology->stream_topology_changed) {
450                 bridge_channel->bridge->technology->stream_topology_changed(
451                         bridge_channel->bridge, bridge_channel);
452         } else {
453                 ast_bridge_channel_stream_map(bridge_channel);
454         }
455 }
456
457 /*!
458  * \internal
459  * \brief Complete joining new channels to the bridge.
460  * \since 12.0.0
461  *
462  * \param bridge Check for new channels on this bridge.
463  *
464  * \note On entry, bridge is already locked.
465  *
466  * \return Nothing
467  */
468 static void bridge_complete_join(struct ast_bridge *bridge)
469 {
470         struct ast_bridge_channel *bridge_channel;
471
472         if (bridge->dissolved) {
473                 /*
474                  * No sense in completing the join on channels for a dissolved
475                  * bridge.  They are just going to be removed soon anyway.
476                  * However, we do have reason to abort here because the bridge
477                  * technology may not be able to handle the number of channels
478                  * still in the bridge.
479                  */
480                 return;
481         }
482
483         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
484                 bridge_channel_queue_deferred_frames(bridge_channel);
485                 if (!bridge_channel->just_joined) {
486                         continue;
487                 }
488                 bridge_channel_complete_join(bridge, bridge_channel);
489         }
490 }
491
492 /*! \brief Helper function used to find the "best" bridge technology given specified capabilities */
493 static struct ast_bridge_technology *find_best_technology(uint32_t capabilities, struct ast_bridge *bridge)
494 {
495         struct ast_bridge_technology *current;
496         struct ast_bridge_technology *best = NULL;
497
498         AST_RWLIST_RDLOCK(&bridge_technologies);
499         AST_RWLIST_TRAVERSE(&bridge_technologies, current, entry) {
500                 if (current->suspended) {
501                         ast_debug(1, "Bridge technology %s is suspended. Skipping.\n",
502                                 current->name);
503                         continue;
504                 }
505                 if (!(current->capabilities & capabilities)) {
506                         ast_debug(1, "Bridge technology %s does not have any capabilities we want.\n",
507                                 current->name);
508                         continue;
509                 }
510                 if (best && current->preference <= best->preference) {
511                         ast_debug(1, "Bridge technology %s has less preference than %s (%u <= %u). Skipping.\n",
512                                 current->name, best->name, current->preference, best->preference);
513                         continue;
514                 }
515                 if (current->compatible && !current->compatible(bridge)) {
516                         ast_debug(1, "Bridge technology %s is not compatible with properties of existing bridge.\n",
517                                 current->name);
518                         continue;
519                 }
520                 best = current;
521         }
522
523         if (best) {
524                 /* Increment it's module reference count if present so it does not get unloaded while in use */
525                 ast_module_ref(best->mod);
526                 ast_debug(1, "Chose bridge technology %s\n", best->name);
527         }
528
529         AST_RWLIST_UNLOCK(&bridge_technologies);
530
531         return best;
532 }
533
534 struct tech_deferred_destroy {
535         struct ast_bridge_technology *tech;
536         void *tech_pvt;
537 };
538
539 /*!
540  * \internal
541  * \brief Deferred destruction of bridge tech private structure.
542  * \since 12.0.0
543  *
544  * \param bridge What to execute the action on.
545  * \param action Deferred bridge tech destruction.
546  *
547  * \note On entry, bridge must not be locked.
548  *
549  * \return Nothing
550  */
551 static void bridge_tech_deferred_destroy(struct ast_bridge *bridge, struct ast_frame *action)
552 {
553         struct tech_deferred_destroy *deferred = action->data.ptr;
554         struct ast_bridge dummy_bridge = {
555                 .technology = deferred->tech,
556                 .tech_pvt = deferred->tech_pvt,
557                 .creator = bridge->creator,
558                 .name = bridge->name,
559                 .uniqueid = bridge->uniqueid,
560                 };
561
562         ast_debug(1, "Bridge %s: calling %s technology destructor (deferred, dummy)\n",
563                 dummy_bridge.uniqueid, dummy_bridge.technology->name);
564         dummy_bridge.technology->destroy(&dummy_bridge);
565         ast_module_unref(dummy_bridge.technology->mod);
566 }
567
568 /*!
569  * \internal
570  * \brief Handle bridge action frame.
571  * \since 12.0.0
572  *
573  * \param bridge What to execute the action on.
574  * \param action What to do.
575  *
576  * \note On entry, bridge is already locked.
577  * \note Can be called by the bridge destructor.
578  *
579  * \return Nothing
580  */
581 static void bridge_action_bridge(struct ast_bridge *bridge, struct ast_frame *action)
582 {
583 #if 0   /* In case we need to know when the destructor is calling us. */
584         int in_destructor = !ao2_ref(bridge, 0);
585 #endif
586
587         switch (action->subclass.integer) {
588         case BRIDGE_CHANNEL_ACTION_DEFERRED_TECH_DESTROY:
589                 ast_bridge_unlock(bridge);
590                 bridge_tech_deferred_destroy(bridge, action);
591                 ast_bridge_lock(bridge);
592                 break;
593         case BRIDGE_CHANNEL_ACTION_DEFERRED_DISSOLVING:
594                 ast_bridge_unlock(bridge);
595                 bridge->v_table->dissolving(bridge);
596                 ast_bridge_lock(bridge);
597                 break;
598         default:
599                 /* Unexpected deferred action type.  Should never happen. */
600                 ast_assert(0);
601                 break;
602         }
603 }
604
605 /*!
606  * \internal
607  * \brief Do any pending bridge actions.
608  * \since 12.0.0
609  *
610  * \param bridge What to do actions on.
611  *
612  * \note On entry, bridge is already locked.
613  * \note Can be called by the bridge destructor.
614  *
615  * \return Nothing
616  */
617 static void bridge_handle_actions(struct ast_bridge *bridge)
618 {
619         struct ast_frame *action;
620
621         while ((action = AST_LIST_REMOVE_HEAD(&bridge->action_queue, frame_list))) {
622                 switch (action->frametype) {
623                 case AST_FRAME_BRIDGE_ACTION:
624                         bridge_action_bridge(bridge, action);
625                         break;
626                 default:
627                         /* Unexpected deferred frame type.  Should never happen. */
628                         ast_assert(0);
629                         break;
630                 }
631                 ast_frfree(action);
632         }
633 }
634
635 static struct stasis_message *create_bridge_snapshot_message(struct ast_bridge *bridge)
636 {
637         RAII_VAR(struct ast_bridge_snapshot *, snapshot, NULL, ao2_cleanup);
638
639         if (!ast_bridge_snapshot_type()) {
640                 return NULL;
641         }
642
643         ast_bridge_lock(bridge);
644         snapshot = ast_bridge_snapshot_create(bridge);
645         ast_bridge_unlock(bridge);
646
647         if (!snapshot) {
648                 return NULL;
649         }
650
651         return stasis_message_create(ast_bridge_snapshot_type(), snapshot);
652 }
653
654 static void destroy_bridge(void *obj)
655 {
656         struct ast_bridge *bridge = obj;
657
658         ast_debug(1, "Bridge %s: actually destroying %s bridge, nobody wants it anymore\n",
659                 bridge->uniqueid, bridge->v_table->name);
660
661         if (bridge->construction_completed) {
662                 RAII_VAR(struct stasis_message *, clear_msg, NULL, ao2_cleanup);
663
664                 clear_msg = create_bridge_snapshot_message(bridge);
665                 if (clear_msg) {
666                         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
667
668                         msg = stasis_cache_clear_create(clear_msg);
669                         if (msg) {
670                                 stasis_publish(ast_bridge_topic(bridge), msg);
671                         }
672                 }
673         }
674
675         /* Do any pending actions in the context of destruction. */
676         ast_bridge_lock(bridge);
677         bridge_handle_actions(bridge);
678         ast_bridge_unlock(bridge);
679
680         /* There should not be any channels left in the bridge. */
681         ast_assert(AST_LIST_EMPTY(&bridge->channels));
682
683         ast_debug(1, "Bridge %s: calling %s bridge destructor\n",
684                 bridge->uniqueid, bridge->v_table->name);
685         bridge->v_table->destroy(bridge);
686
687         /* Pass off the bridge to the technology to destroy if needed */
688         if (bridge->technology) {
689                 ast_debug(1, "Bridge %s: calling %s technology stop\n",
690                         bridge->uniqueid, bridge->technology->name);
691                 if (bridge->technology->stop) {
692                         ast_bridge_lock(bridge);
693                         bridge->technology->stop(bridge);
694                         ast_bridge_unlock(bridge);
695                 }
696                 ast_debug(1, "Bridge %s: calling %s technology destructor\n",
697                         bridge->uniqueid, bridge->technology->name);
698                 if (bridge->technology->destroy) {
699                         bridge->technology->destroy(bridge);
700                 }
701                 ast_module_unref(bridge->technology->mod);
702                 bridge->technology = NULL;
703         }
704
705         AST_VECTOR_FREE(&bridge->media_types);
706
707         bridge->callid = 0;
708
709         cleanup_video_mode(bridge);
710
711         stasis_cp_single_unsubscribe(bridge->topics);
712
713         ast_string_field_free_memory(bridge);
714 }
715
716 struct ast_bridge *bridge_register(struct ast_bridge *bridge)
717 {
718         if (bridge) {
719                 bridge->construction_completed = 1;
720                 ast_bridge_lock(bridge);
721                 ast_bridge_publish_state(bridge);
722                 ast_bridge_unlock(bridge);
723                 if (!ao2_link(bridges, bridge)) {
724                         ast_bridge_destroy(bridge, 0);
725                         bridge = NULL;
726                 }
727         }
728         return bridge;
729 }
730
731 struct ast_bridge *bridge_alloc(size_t size, const struct ast_bridge_methods *v_table)
732 {
733         struct ast_bridge *bridge;
734
735         /* Check v_table that all methods are present. */
736         if (!v_table
737                 || !v_table->name
738                 || !v_table->destroy
739                 || !v_table->dissolving
740                 || !v_table->push
741                 || !v_table->pull
742                 || !v_table->notify_masquerade
743                 || !v_table->get_merge_priority) {
744                 ast_log(LOG_ERROR, "Virtual method table for bridge class %s not complete.\n",
745                         v_table && v_table->name ? v_table->name : "<unknown>");
746                 ast_assert(0);
747                 return NULL;
748         }
749
750         bridge = ao2_alloc(size, destroy_bridge);
751         if (!bridge) {
752                 return NULL;
753         }
754
755         if (ast_string_field_init(bridge, 80)) {
756                 ao2_cleanup(bridge);
757                 return NULL;
758         }
759
760         bridge->v_table = v_table;
761
762         AST_VECTOR_INIT(&bridge->media_types, AST_MEDIA_TYPE_END);
763
764         return bridge;
765 }
766
767 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)
768 {
769         char uuid_hold[AST_UUID_STR_LEN];
770
771         if (!self) {
772                 return NULL;
773         }
774
775         if (!ast_strlen_zero(id)) {
776                 ast_string_field_set(self, uniqueid, id);
777         } else {
778                 ast_uuid_generate_str(uuid_hold, AST_UUID_STR_LEN);
779                 ast_string_field_set(self, uniqueid, uuid_hold);
780         }
781         ast_string_field_set(self, creator, creator);
782         if (!ast_strlen_zero(creator)) {
783                 ast_string_field_set(self, name, name);
784         }
785
786         ast_set_flag(&self->feature_flags, flags);
787         self->allowed_capabilities = capabilities;
788
789         if (!(flags & AST_BRIDGE_FLAG_INVISIBLE)) {
790                 if (bridge_topics_init(self) != 0) {
791                         ast_log(LOG_WARNING, "Bridge %s: Could not initialize topics\n",
792                                 self->uniqueid);
793                         ao2_ref(self, -1);
794                         return NULL;
795                 }
796         }
797
798         /* Use our helper function to find the "best" bridge technology. */
799         self->technology = find_best_technology(capabilities, self);
800         if (!self->technology) {
801                 ast_log(LOG_WARNING, "Bridge %s: Could not create class %s.  No technology to support it.\n",
802                         self->uniqueid, self->v_table->name);
803                 ao2_ref(self, -1);
804                 return NULL;
805         }
806
807         /* Pass off the bridge to the technology to manipulate if needed */
808         ast_debug(1, "Bridge %s: calling %s technology constructor\n",
809                 self->uniqueid, self->technology->name);
810         if (self->technology->create && self->technology->create(self)) {
811                 ast_log(LOG_WARNING, "Bridge %s: failed to setup bridge technology %s\n",
812                         self->uniqueid, self->technology->name);
813                 ao2_ref(self, -1);
814                 return NULL;
815         }
816         ast_debug(1, "Bridge %s: calling %s technology start\n",
817                 self->uniqueid, self->technology->name);
818         if (self->technology->start && self->technology->start(self)) {
819                 ast_log(LOG_WARNING, "Bridge %s: failed to start bridge technology %s\n",
820                         self->uniqueid, self->technology->name);
821                 ao2_ref(self, -1);
822                 return NULL;
823         }
824
825         if (!(flags & AST_BRIDGE_FLAG_INVISIBLE)) {
826                 if (!ast_bridge_topic(self)) {
827                         ao2_ref(self, -1);
828                         return NULL;
829                 }
830         }
831
832         return self;
833 }
834
835 /*!
836  * \internal
837  * \brief ast_bridge base class destructor.
838  * \since 12.0.0
839  *
840  * \param self Bridge to operate upon.
841  *
842  * \note Stub because of nothing to do.
843  *
844  * \return Nothing
845  */
846 static void bridge_base_destroy(struct ast_bridge *self)
847 {
848 }
849
850 /*!
851  * \internal
852  * \brief The bridge is being dissolved.
853  * \since 12.0.0
854  *
855  * \param self Bridge to operate upon.
856  *
857  * \return Nothing
858  */
859 static void bridge_base_dissolving(struct ast_bridge *self)
860 {
861         ao2_unlink(bridges, self);
862 }
863
864 /*!
865  * \internal
866  * \brief ast_bridge base push method.
867  * \since 12.0.0
868  *
869  * \param self Bridge to operate upon.
870  * \param bridge_channel Bridge channel to push.
871  * \param swap Bridge channel to swap places with if not NULL.
872  *
873  * \note On entry, self is already locked.
874  * \note Stub because of nothing to do.
875  *
876  * \retval 0 on success
877  * \retval -1 on failure
878  */
879 static int bridge_base_push(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
880 {
881         return 0;
882 }
883
884 /*!
885  * \internal
886  * \brief ast_bridge base pull method.
887  * \since 12.0.0
888  *
889  * \param self Bridge to operate upon.
890  * \param bridge_channel Bridge channel to pull.
891  *
892  * \note On entry, self is already locked.
893  *
894  * \return Nothing
895  */
896 static void bridge_base_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
897 {
898         ast_bridge_features_remove(bridge_channel->features, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
899 }
900
901 /*!
902  * \internal
903  * \brief ast_bridge base notify_masquerade method.
904  * \since 12.0.0
905  *
906  * \param self Bridge to operate upon.
907  * \param bridge_channel Bridge channel that was masqueraded.
908  *
909  * \note On entry, self is already locked.
910  *
911  * \return Nothing
912  */
913 static void bridge_base_notify_masquerade(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
914 {
915         self->reconfigured = 1;
916 }
917
918 /*!
919  * \internal
920  * \brief Get the merge priority of this bridge.
921  * \since 12.0.0
922  *
923  * \param self Bridge to operate upon.
924  *
925  * \note On entry, self is already locked.
926  *
927  * \return Merge priority
928  */
929 static int bridge_base_get_merge_priority(struct ast_bridge *self)
930 {
931         return 0;
932 }
933
934 /*!
935  * \internal
936  * \brief ast_bridge base push_peek method.
937  * \since 13.2.0
938  *
939  * \param self Bridge to operate upon.
940  * \param bridge_channel Bridge channel to push.
941  * \param swap Bridge channel to swap places with if not NULL.
942  *
943  * \note On entry, self is already locked.
944  * \note Stub because of nothing to do.
945  *
946  * \retval 0 on success
947  * \retval -1 on failure
948  */
949 static int bridge_base_push_peek(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
950 {
951         return 0;
952 }
953
954 struct ast_bridge_methods ast_bridge_base_v_table = {
955         .name = "base",
956         .destroy = bridge_base_destroy,
957         .dissolving = bridge_base_dissolving,
958         .push = bridge_base_push,
959         .pull = bridge_base_pull,
960         .notify_masquerade = bridge_base_notify_masquerade,
961         .get_merge_priority = bridge_base_get_merge_priority,
962         .push_peek = bridge_base_push_peek,
963 };
964
965 struct ast_bridge *ast_bridge_base_new(uint32_t capabilities, unsigned int flags, const char *creator, const char *name, const char *id)
966 {
967         void *bridge;
968
969         bridge = bridge_alloc(sizeof(struct ast_bridge), &ast_bridge_base_v_table);
970         bridge = bridge_base_init(bridge, capabilities, flags, creator, name, id);
971         bridge = bridge_register(bridge);
972         return bridge;
973 }
974
975 int ast_bridge_destroy(struct ast_bridge *bridge, int cause)
976 {
977         ast_debug(1, "Bridge %s: telling all channels to leave the party\n", bridge->uniqueid);
978         ast_bridge_lock(bridge);
979         bridge_dissolve(bridge, cause);
980         ast_bridge_unlock(bridge);
981
982         ao2_ref(bridge, -1);
983
984         return 0;
985 }
986
987 /*!
988  * \internal
989  * \brief Perform the smart bridge operation.
990  * \since 12.0.0
991  *
992  * \param bridge Work on this bridge.
993  *
994  * \details
995  * Basically see if a new bridge technology should be used instead
996  * of the current one.
997  *
998  * \note On entry, bridge is already locked.
999  *
1000  * \retval 0 on success.
1001  * \retval -1 on error.
1002  */
1003 static int smart_bridge_operation(struct ast_bridge *bridge)
1004 {
1005         uint32_t new_capabilities;
1006         struct ast_bridge_technology *new_technology;
1007         struct ast_bridge_technology *old_technology = bridge->technology;
1008         struct ast_bridge_channel *bridge_channel;
1009         struct ast_frame *deferred_action;
1010         struct ast_bridge dummy_bridge = {
1011                 .technology = bridge->technology,
1012                 .tech_pvt = bridge->tech_pvt,
1013                 .creator = bridge->creator,
1014                 .name = bridge->name,
1015                 .uniqueid = bridge->uniqueid,
1016         };
1017
1018         if (bridge->dissolved) {
1019                 ast_debug(1, "Bridge %s is dissolved, not performing smart bridge operation.\n",
1020                         bridge->uniqueid);
1021                 return 0;
1022         }
1023
1024         /* Determine new bridge technology capabilities needed. */
1025         if (2 < bridge->num_channels) {
1026                 new_capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX;
1027                 new_capabilities &= bridge->allowed_capabilities;
1028         } else {
1029                 new_capabilities = AST_BRIDGE_CAPABILITY_NATIVE | AST_BRIDGE_CAPABILITY_1TO1MIX;
1030                 new_capabilities &= bridge->allowed_capabilities;
1031                 if (!new_capabilities
1032                         && (bridge->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
1033                         /* Allow switching between different multimix bridge technologies. */
1034                         new_capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX;
1035                 }
1036         }
1037
1038         /* Find a bridge technology to satisfy the new capabilities. */
1039         new_technology = find_best_technology(new_capabilities, bridge);
1040         if (!new_technology) {
1041                 int is_compatible = 0;
1042
1043                 if (old_technology->compatible) {
1044                         is_compatible = old_technology->compatible(bridge);
1045                 } else if (old_technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX) {
1046                         is_compatible = 1;
1047                 } else if (bridge->num_channels <= 2
1048                         && (old_technology->capabilities & AST_BRIDGE_CAPABILITY_1TO1MIX)) {
1049                         is_compatible = 1;
1050                 }
1051
1052                 if (is_compatible) {
1053                         ast_debug(1, "Bridge %s could not get a new technology, staying with old technology.\n",
1054                                 bridge->uniqueid);
1055                         return 0;
1056                 }
1057                 ast_log(LOG_WARNING, "Bridge %s has no technology available to support it.\n",
1058                         bridge->uniqueid);
1059                 return -1;
1060         }
1061         if (new_technology == old_technology) {
1062                 ast_debug(1, "Bridge %s is already using the new technology.\n",
1063                         bridge->uniqueid);
1064                 ast_module_unref(old_technology->mod);
1065                 return 0;
1066         }
1067
1068         if (old_technology->destroy) {
1069                 struct tech_deferred_destroy deferred_tech_destroy = {
1070                         .tech = dummy_bridge.technology,
1071                         .tech_pvt = dummy_bridge.tech_pvt,
1072                 };
1073                 struct ast_frame action = {
1074                         .frametype = AST_FRAME_BRIDGE_ACTION,
1075                         .subclass.integer = BRIDGE_CHANNEL_ACTION_DEFERRED_TECH_DESTROY,
1076                         .data.ptr = &deferred_tech_destroy,
1077                         .datalen = sizeof(deferred_tech_destroy),
1078                 };
1079
1080                 /*
1081                  * We need to defer the bridge technology destroy callback
1082                  * because we have the bridge locked.
1083                  */
1084                 deferred_action = ast_frdup(&action);
1085                 if (!deferred_action) {
1086                         ast_module_unref(new_technology->mod);
1087                         return -1;
1088                 }
1089         } else {
1090                 deferred_action = NULL;
1091         }
1092
1093         /*
1094          * We are now committed to changing the bridge technology.  We
1095          * must not release the bridge lock until we have installed the
1096          * new bridge technology.
1097          */
1098         ast_verb(4, "Bridge %s: switching from %s technology to %s\n",
1099                 bridge->uniqueid, old_technology->name, new_technology->name);
1100
1101         /*
1102          * Since we are soon going to pass this bridge to a new
1103          * technology we need to NULL out the tech_pvt pointer but
1104          * don't worry as it still exists in dummy_bridge, ditto for the
1105          * old technology.
1106          */
1107         bridge->tech_pvt = NULL;
1108         bridge->technology = new_technology;
1109
1110         /* Setup the new bridge technology. */
1111         ast_debug(1, "Bridge %s: calling %s technology constructor\n",
1112                 bridge->uniqueid, new_technology->name);
1113         if (new_technology->create && new_technology->create(bridge)) {
1114                 ast_log(LOG_WARNING, "Bridge %s: failed to setup bridge technology %s\n",
1115                         bridge->uniqueid, new_technology->name);
1116                 bridge->tech_pvt = dummy_bridge.tech_pvt;
1117                 bridge->technology = dummy_bridge.technology;
1118                 ast_module_unref(new_technology->mod);
1119                 return -1;
1120         }
1121
1122         /* To ensure that things are sane for the old technology move the channels it
1123          * expects to the dummy bridge
1124          */
1125         AST_LIST_TRAVERSE_SAFE_BEGIN(&bridge->channels, bridge_channel, entry) {
1126                 if (bridge_channel->just_joined) {
1127                         continue;
1128                 }
1129                 ast_debug(1, "Bridge %s: moving %p(%s) to dummy bridge temporarily\n",
1130                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1131                 AST_LIST_REMOVE_CURRENT(entry);
1132                 AST_LIST_INSERT_TAIL(&dummy_bridge.channels, bridge_channel, entry);
1133                 dummy_bridge.num_channels++;
1134                 if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1135                         dummy_bridge.num_lonely++;
1136                 }
1137                 if (!bridge_channel->suspended) {
1138                         dummy_bridge.num_active++;
1139                 }
1140         }
1141         AST_LIST_TRAVERSE_SAFE_END;
1142
1143         /* Take all the channels out of the old technology */
1144         AST_LIST_TRAVERSE_SAFE_BEGIN(&dummy_bridge.channels, bridge_channel, entry) {
1145                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology (dummy)\n",
1146                         dummy_bridge.uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1147                         old_technology->name);
1148                 if (old_technology->leave) {
1149                         old_technology->leave(&dummy_bridge, bridge_channel);
1150                 }
1151                 AST_LIST_REMOVE_CURRENT(entry);
1152                 AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
1153                 dummy_bridge.num_channels--;
1154                 if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1155                         dummy_bridge.num_lonely--;
1156                 }
1157                 if (!bridge_channel->suspended) {
1158                         dummy_bridge.num_active--;
1159                 }
1160         }
1161         AST_LIST_TRAVERSE_SAFE_END;
1162
1163         ast_debug(1, "Bridge %s: calling %s technology stop\n",
1164                 dummy_bridge.uniqueid, old_technology->name);
1165         if (old_technology->stop) {
1166                 old_technology->stop(&dummy_bridge);
1167         }
1168
1169         /* Add any new channels or re-add existing channels to the bridge. */
1170         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1171                 bridge_channel_complete_join(bridge, bridge_channel);
1172         }
1173
1174         ast_debug(1, "Bridge %s: calling %s technology start\n",
1175                 bridge->uniqueid, new_technology->name);
1176         if (new_technology->start && new_technology->start(bridge)) {
1177                 ast_log(LOG_WARNING, "Bridge %s: failed to start bridge technology %s\n",
1178                         bridge->uniqueid, new_technology->name);
1179         }
1180
1181         /*
1182          * Now that all the channels have been moved over we need to get
1183          * rid of all the information the old technology may have left
1184          * around.
1185          */
1186         if (old_technology->destroy) {
1187                 ast_debug(1, "Bridge %s: deferring %s technology destructor\n",
1188                         dummy_bridge.uniqueid, old_technology->name);
1189                 bridge_queue_action_nodup(bridge, deferred_action);
1190         } else {
1191                 ast_debug(1, "Bridge %s: calling %s technology destructor\n",
1192                         dummy_bridge.uniqueid, old_technology->name);
1193                 ast_module_unref(old_technology->mod);
1194         }
1195
1196         return 0;
1197 }
1198
1199 /*!
1200  * \internal
1201  * \brief Bridge channel to check if a BRIDGE_PLAY_SOUND needs to be played.
1202  * \since 12.0.0
1203  *
1204  * \param bridge_channel What to check.
1205  *
1206  * \return Nothing
1207  */
1208 static void check_bridge_play_sound(struct ast_bridge_channel *bridge_channel)
1209 {
1210         const char *play_file;
1211
1212         ast_channel_lock(bridge_channel->chan);
1213         play_file = pbx_builtin_getvar_helper(bridge_channel->chan, "BRIDGE_PLAY_SOUND");
1214         if (!ast_strlen_zero(play_file)) {
1215                 play_file = ast_strdupa(play_file);
1216                 pbx_builtin_setvar_helper(bridge_channel->chan, "BRIDGE_PLAY_SOUND", NULL);
1217         } else {
1218                 play_file = NULL;
1219         }
1220         ast_channel_unlock(bridge_channel->chan);
1221
1222         if (play_file) {
1223                 ast_bridge_channel_queue_playfile(bridge_channel, NULL, play_file, NULL);
1224         }
1225 }
1226
1227 /*!
1228  * \internal
1229  * \brief Check for any BRIDGE_PLAY_SOUND channel variables in the bridge.
1230  * \since 12.0.0
1231  *
1232  * \param bridge What to operate on.
1233  *
1234  * \note On entry, the bridge is already locked.
1235  *
1236  * \return Nothing
1237  */
1238 static void check_bridge_play_sounds(struct ast_bridge *bridge)
1239 {
1240         struct ast_bridge_channel *bridge_channel;
1241
1242         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1243                 check_bridge_play_sound(bridge_channel);
1244         }
1245 }
1246
1247 void ast_bridge_vars_set(struct ast_channel *chan, const char *name, const char *pvtid)
1248 {
1249         ast_channel_stage_snapshot(chan);
1250         pbx_builtin_setvar_helper(chan, "BRIDGEPEER", name);
1251         pbx_builtin_setvar_helper(chan, "BRIDGEPVTCALLID", pvtid);
1252         ast_channel_stage_snapshot_done(chan);
1253 }
1254
1255 /*!
1256  * \internal
1257  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a 2 party bridge.
1258  * \since 12.0.0
1259  *
1260  * \param c0 Party of the first part.
1261  * \param c1 Party of the second part.
1262  *
1263  * \note On entry, the bridge is already locked.
1264  * \note The bridge is expected to have exactly two parties.
1265  *
1266  * \return Nothing
1267  */
1268 static void set_bridge_peer_vars_2party(struct ast_channel *c0, struct ast_channel *c1)
1269 {
1270         const char *c0_name;
1271         const char *c1_name;
1272         const char *c0_pvtid = NULL;
1273         const char *c1_pvtid = NULL;
1274 #define UPDATE_BRIDGE_VARS_GET(chan, name, pvtid)                                                                       \
1275         do {                                                                                                                                                    \
1276                 name = ast_strdupa(ast_channel_name(chan));                                                                     \
1277                 if (ast_channel_tech(chan)->get_pvt_uniqueid) {                                                         \
1278                         pvtid = ast_strdupa(ast_channel_tech(chan)->get_pvt_uniqueid(chan));    \
1279                 }                                                                                                                                                       \
1280         } while (0)
1281
1282         ast_channel_lock(c1);
1283         UPDATE_BRIDGE_VARS_GET(c1, c1_name, c1_pvtid);
1284         ast_channel_unlock(c1);
1285
1286         ast_channel_lock(c0);
1287         ast_bridge_vars_set(c0, c1_name, c1_pvtid);
1288         UPDATE_BRIDGE_VARS_GET(c0, c0_name, c0_pvtid);
1289         ast_channel_unlock(c0);
1290
1291         ast_channel_lock(c1);
1292         ast_bridge_vars_set(c1, c0_name, c0_pvtid);
1293         ast_channel_unlock(c1);
1294 }
1295
1296 /*!
1297  * \internal
1298  * \brief Fill the BRIDGEPEER value buffer with a comma separated list of channel names.
1299  * \since 12.0.0
1300  *
1301  * \param buf Buffer to fill.  The caller must guarantee the buffer is large enough.
1302  * \param cur_idx Which index into names[] to skip.
1303  * \param names Channel names to put in the buffer.
1304  * \param num_names Number of names in the array.
1305  *
1306  * \return Nothing
1307  */
1308 static void fill_bridgepeer_buf(char *buf, unsigned int cur_idx, const char *names[], unsigned int num_names)
1309 {
1310         int need_separator = 0;
1311         unsigned int idx;
1312         const char *src;
1313         char *pos;
1314
1315         pos = buf;
1316         for (idx = 0; idx < num_names; ++idx) {
1317                 if (idx == cur_idx) {
1318                         continue;
1319                 }
1320
1321                 if (need_separator) {
1322                         *pos++ = ',';
1323                 }
1324                 need_separator = 1;
1325
1326                 /* Copy name into buffer. */
1327                 src = names[idx];
1328                 while (*src) {
1329                         *pos++ = *src++;
1330                 }
1331         }
1332         *pos = '\0';
1333 }
1334
1335 /*!
1336  * \internal
1337  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a multi-party bridge.
1338  * \since 12.0.0
1339  *
1340  * \param bridge What to operate on.
1341  *
1342  * \note On entry, the bridge is already locked.
1343  * \note The bridge is expected to have more than two parties.
1344  *
1345  * \return Nothing
1346  */
1347 static void set_bridge_peer_vars_multiparty(struct ast_bridge *bridge)
1348 {
1349 /*
1350  * Set a maximum number of channel names for the BRIDGEPEER
1351  * list.  The plus one is for the current channel which is not
1352  * put in the list.
1353  */
1354 #define MAX_BRIDGEPEER_CHANS    (10 + 1)
1355
1356         unsigned int idx;
1357         unsigned int num_names;
1358         unsigned int len;
1359         const char **names;
1360         char *buf;
1361         struct ast_bridge_channel *bridge_channel;
1362
1363         /* Get first MAX_BRIDGEPEER_CHANS channel names. */
1364         num_names = MIN(bridge->num_channels, MAX_BRIDGEPEER_CHANS);
1365         names = ast_alloca(num_names * sizeof(*names));
1366         idx = 0;
1367         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1368                 if (num_names <= idx) {
1369                         break;
1370                 }
1371                 ast_channel_lock(bridge_channel->chan);
1372                 names[idx++] = ast_strdupa(ast_channel_name(bridge_channel->chan));
1373                 ast_channel_unlock(bridge_channel->chan);
1374         }
1375
1376         /* Determine maximum buf size needed. */
1377         len = num_names;
1378         for (idx = 0; idx < num_names; ++idx) {
1379                 len += strlen(names[idx]);
1380         }
1381         buf = ast_alloca(len);
1382
1383         /* Set the bridge channel variables. */
1384         idx = 0;
1385         buf[0] = '\0';
1386         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1387                 if (idx < num_names) {
1388                         fill_bridgepeer_buf(buf, idx, names, num_names);
1389                 }
1390                 ++idx;
1391
1392                 ast_channel_lock(bridge_channel->chan);
1393                 ast_bridge_vars_set(bridge_channel->chan, buf, NULL);
1394                 ast_channel_unlock(bridge_channel->chan);
1395         }
1396 }
1397
1398 /*!
1399  * \internal
1400  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a holding bridge.
1401  * \since 12.0.0
1402  *
1403  * \param bridge What to operate on.
1404  *
1405  * \note On entry, the bridge is already locked.
1406  *
1407  * \return Nothing
1408  */
1409 static void set_bridge_peer_vars_holding(struct ast_bridge *bridge)
1410 {
1411         struct ast_bridge_channel *bridge_channel;
1412
1413         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1414                 ast_channel_lock(bridge_channel->chan);
1415                 ast_bridge_vars_set(bridge_channel->chan, NULL, NULL);
1416                 ast_channel_unlock(bridge_channel->chan);
1417         }
1418 }
1419
1420 /*!
1421  * \internal
1422  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in the bridge.
1423  * \since 12.0.0
1424  *
1425  * \param bridge What to operate on.
1426  *
1427  * \note On entry, the bridge is already locked.
1428  *
1429  * \return Nothing
1430  */
1431 static void set_bridge_peer_vars(struct ast_bridge *bridge)
1432 {
1433         if (bridge->technology->capabilities & AST_BRIDGE_CAPABILITY_HOLDING) {
1434                 set_bridge_peer_vars_holding(bridge);
1435                 return;
1436         }
1437         if (bridge->num_channels < 2) {
1438                 return;
1439         }
1440         if (bridge->num_channels == 2) {
1441                 set_bridge_peer_vars_2party(AST_LIST_FIRST(&bridge->channels)->chan,
1442                         AST_LIST_LAST(&bridge->channels)->chan);
1443         } else {
1444                 set_bridge_peer_vars_multiparty(bridge);
1445         }
1446 }
1447
1448 void bridge_reconfigured(struct ast_bridge *bridge, unsigned int colp_update)
1449 {
1450         if (!bridge->reconfigured) {
1451                 return;
1452         }
1453         bridge->reconfigured = 0;
1454         if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_SMART)
1455                 && smart_bridge_operation(bridge)) {
1456                 /* Smart bridge failed. */
1457                 bridge_dissolve(bridge, 0);
1458                 return;
1459         }
1460         bridge_complete_join(bridge);
1461
1462         if (bridge->dissolved) {
1463                 return;
1464         }
1465         check_bridge_play_sounds(bridge);
1466         set_bridge_peer_vars(bridge);
1467         ast_bridge_publish_state(bridge);
1468
1469         if (colp_update) {
1470                 bridge_reconfigured_connected_line_update(bridge);
1471         }
1472 }
1473
1474 struct ast_bridge_channel *bridge_find_channel(struct ast_bridge *bridge, struct ast_channel *chan)
1475 {
1476         struct ast_bridge_channel *bridge_channel;
1477
1478         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1479                 if (bridge_channel->chan == chan) {
1480                         break;
1481                 }
1482         }
1483
1484         return bridge_channel;
1485 }
1486
1487 void ast_bridge_notify_masquerade(struct ast_channel *chan)
1488 {
1489         struct ast_bridge_channel *bridge_channel;
1490         struct ast_bridge *bridge;
1491
1492         /* Safely get the bridge_channel pointer for the chan. */
1493         ast_channel_lock(chan);
1494         bridge_channel = ast_channel_get_bridge_channel(chan);
1495         ast_channel_unlock(chan);
1496         if (!bridge_channel) {
1497                 /* Not in a bridge */
1498                 return;
1499         }
1500
1501         ast_bridge_channel_lock_bridge(bridge_channel);
1502         bridge = bridge_channel->bridge;
1503         if (bridge_channel == bridge_find_channel(bridge, chan)) {
1504 /*
1505  * XXX ASTERISK-22366 this needs more work.  The channels need
1506  * to be made compatible again if the formats change. The
1507  * bridge_channel thread needs to monitor for this case.
1508  */
1509                 /* The channel we want to notify is still in a bridge. */
1510                 bridge->v_table->notify_masquerade(bridge, bridge_channel);
1511                 bridge_reconfigured(bridge, 1);
1512         }
1513         ast_bridge_unlock(bridge);
1514         ao2_ref(bridge_channel, -1);
1515 }
1516
1517 /*!
1518  * \brief Internal bridge impart wait condition and associated conditional.
1519  */
1520 struct bridge_channel_impart_cond {
1521         AST_LIST_ENTRY(bridge_channel_impart_cond) node;
1522         /*! Lock for the data structure */
1523         ast_mutex_t lock;
1524         /*! Wait condition */
1525         ast_cond_t cond;
1526         /*! Wait until done */
1527         int done;
1528 };
1529
1530 AST_LIST_HEAD_NOLOCK(bridge_channel_impart_ds_head, bridge_channel_impart_cond);
1531
1532 /*!
1533  * \internal
1534  * \brief Signal imparting threads to wake up.
1535  * \since 13.9.0
1536  *
1537  * \param ds_head List of imparting threads to wake up.
1538  *
1539  * \return Nothing
1540  */
1541 static void bridge_channel_impart_ds_head_signal(struct bridge_channel_impart_ds_head *ds_head)
1542 {
1543         if (ds_head) {
1544                 struct bridge_channel_impart_cond *cond;
1545
1546                 while ((cond = AST_LIST_REMOVE_HEAD(ds_head, node))) {
1547                         ast_mutex_lock(&cond->lock);
1548                         cond->done = 1;
1549                         ast_cond_signal(&cond->cond);
1550                         ast_mutex_unlock(&cond->lock);
1551                 }
1552         }
1553 }
1554
1555 static void bridge_channel_impart_ds_head_dtor(void *doomed)
1556 {
1557         bridge_channel_impart_ds_head_signal(doomed);
1558         ast_free(doomed);
1559 }
1560
1561 /*!
1562  * \internal
1563  * \brief Fixup the bridge impart datastore.
1564  * \since 13.9.0
1565  *
1566  * \param data Bridge impart datastore data to fixup from old_chan.
1567  * \param old_chan The datastore is moving from this channel.
1568  * \param new_chan The datastore is moving to this channel.
1569  *
1570  * \return Nothing
1571  */
1572 static void bridge_channel_impart_ds_head_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan)
1573 {
1574         /*
1575          * Signal any waiting impart threads.  The masquerade is going to kill
1576          * old_chan and we don't need to be waiting on new_chan.
1577          */
1578         bridge_channel_impart_ds_head_signal(data);
1579 }
1580
1581 static const struct ast_datastore_info bridge_channel_impart_ds_info = {
1582         .type = "bridge-impart-ds",
1583         .destroy = bridge_channel_impart_ds_head_dtor,
1584         .chan_fixup = bridge_channel_impart_ds_head_fixup,
1585 };
1586
1587 /*!
1588  * \internal
1589  * \brief Add impart wait datastore conditional to channel.
1590  * \since 13.9.0
1591  *
1592  * \param chan Channel to add the impart wait conditional.
1593  * \param cond Imparting conditional to add.
1594  *
1595  * \retval 0 on success.
1596  * \retval -1 on error.
1597  */
1598 static int bridge_channel_impart_add(struct ast_channel *chan, struct bridge_channel_impart_cond *cond)
1599 {
1600         struct ast_datastore *datastore;
1601         struct bridge_channel_impart_ds_head *ds_head;
1602
1603         ast_channel_lock(chan);
1604
1605         datastore = ast_channel_datastore_find(chan, &bridge_channel_impart_ds_info, NULL);
1606         if (!datastore) {
1607                 datastore = ast_datastore_alloc(&bridge_channel_impart_ds_info, NULL);
1608                 if (!datastore) {
1609                         ast_channel_unlock(chan);
1610                         return -1;
1611                 }
1612                 ds_head = ast_calloc(1, sizeof(*ds_head));
1613                 if (!ds_head) {
1614                         ast_channel_unlock(chan);
1615                         ast_datastore_free(datastore);
1616                         return -1;
1617                 }
1618                 datastore->data = ds_head;
1619                 ast_channel_datastore_add(chan, datastore);
1620         } else {
1621                 ds_head = datastore->data;
1622                 ast_assert(ds_head != NULL);
1623         }
1624
1625         AST_LIST_INSERT_TAIL(ds_head, cond, node);
1626
1627         ast_channel_unlock(chan);
1628         return 0;
1629 }
1630
1631 void bridge_channel_impart_signal(struct ast_channel *chan)
1632 {
1633         struct ast_datastore *datastore;
1634
1635         ast_channel_lock(chan);
1636         datastore = ast_channel_datastore_find(chan, &bridge_channel_impart_ds_info, NULL);
1637         if (datastore) {
1638                 bridge_channel_impart_ds_head_signal(datastore->data);
1639         }
1640         ast_channel_unlock(chan);
1641 }
1642
1643 /*!
1644  * \internal
1645  * \brief Block imparting channel thread until signaled.
1646  * \since 13.9.0
1647  *
1648  * \param cond Imparting conditional to wait for.
1649  *
1650  * \return Nothing
1651  */
1652 static void bridge_channel_impart_wait(struct bridge_channel_impart_cond *cond)
1653 {
1654         ast_mutex_lock(&cond->lock);
1655         while (!cond->done) {
1656                 ast_cond_wait(&cond->cond, &cond->lock);
1657         }
1658         ast_mutex_unlock(&cond->lock);
1659 }
1660
1661 /*
1662  * XXX ASTERISK-21271 make ast_bridge_join() require features to be allocated just like ast_bridge_impart() and not expect the struct back.
1663  *
1664  * This change is really going to break ConfBridge.  All other
1665  * users are easily changed.  However, it is needed so the
1666  * bridging code can manipulate features on all channels
1667  * consistently no matter how they joined.
1668  *
1669  * Need to update the features parameter doxygen when this
1670  * change is made to be like ast_bridge_impart().
1671  */
1672 int ast_bridge_join(struct ast_bridge *bridge,
1673         struct ast_channel *chan,
1674         struct ast_channel *swap,
1675         struct ast_bridge_features *features,
1676         struct ast_bridge_tech_optimizations *tech_args,
1677         enum ast_bridge_join_flags flags)
1678 {
1679         struct ast_bridge_channel *bridge_channel;
1680         int res = 0;
1681
1682         bridge_channel = bridge_channel_internal_alloc(bridge);
1683         if (flags & AST_BRIDGE_JOIN_PASS_REFERENCE) {
1684                 ao2_ref(bridge, -1);
1685         }
1686         if (!bridge_channel) {
1687                 ao2_t_cleanup(swap, "Error exit: bridge_channel alloc failed");
1688                 res = -1;
1689                 goto join_exit;
1690         }
1691 /* 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. */
1692         ast_assert(features != NULL);
1693         if (!features) {
1694                 ao2_ref(bridge_channel, -1);
1695                 ao2_t_cleanup(swap, "Error exit: features is NULL");
1696                 res = -1;
1697                 goto join_exit;
1698         }
1699         if (tech_args) {
1700                 bridge_channel->tech_args = *tech_args;
1701         }
1702
1703         ast_channel_lock(chan);
1704         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE)) {
1705                 res = -1;
1706         } else {
1707                 ast_channel_internal_bridge_channel_set(chan, bridge_channel);
1708         }
1709         ast_channel_unlock(chan);
1710         bridge_channel->thread = pthread_self();
1711         bridge_channel->chan = chan;
1712         bridge_channel->swap = swap;
1713         bridge_channel->features = features;
1714         bridge_channel->inhibit_colp = !!(flags & AST_BRIDGE_JOIN_INHIBIT_JOIN_COLP);
1715
1716         /* allow subclass to peek at upcoming push operation */
1717         if (bridge->v_table->push_peek && !res) {
1718                 struct ast_bridge_channel *bcswap = NULL;
1719
1720                 ast_bridge_lock(bridge);
1721                 if (bridge_channel->swap) {
1722                         bcswap = bridge_find_channel(bridge, bridge_channel->swap);
1723                 }
1724                 res = bridge->v_table->push_peek(bridge, bridge_channel, bcswap);
1725                 ast_bridge_unlock(bridge);
1726         }
1727
1728         if (!res) {
1729                 res = bridge_channel_internal_join(bridge_channel);
1730         }
1731
1732         /* Cleanup all the data in the bridge channel after it leaves the bridge. */
1733         ast_channel_lock(chan);
1734         ast_channel_internal_bridge_channel_set(chan, NULL);
1735         ast_channel_unlock(chan);
1736         bridge_channel->chan = NULL;
1737         /* If bridge_channel->swap is not NULL then the join failed. */
1738         ao2_t_cleanup(bridge_channel->swap, "Bridge complete: join failed");
1739         bridge_channel->swap = NULL;
1740         bridge_channel->features = NULL;
1741
1742         ao2_ref(bridge_channel, -1);
1743
1744 join_exit:
1745         ast_bridge_run_after_callback(chan);
1746         bridge_channel_impart_signal(chan);
1747         if (!(ast_channel_softhangup_internal_flag(chan) & AST_SOFTHANGUP_ASYNCGOTO)
1748                 && !ast_bridge_setup_after_goto(chan)) {
1749                 /* Claim the after bridge goto is an async goto destination. */
1750                 ast_channel_lock(chan);
1751                 ast_softhangup_nolock(chan, AST_SOFTHANGUP_ASYNCGOTO);
1752                 ast_channel_unlock(chan);
1753         }
1754         return res;
1755 }
1756
1757 /*! \brief Thread responsible for imparted bridged channels to be departed */
1758 static void *bridge_channel_depart_thread(void *data)
1759 {
1760         struct ast_bridge_channel *bridge_channel = data;
1761         int res = 0;
1762
1763         if (bridge_channel->callid) {
1764                 ast_callid_threadassoc_add(bridge_channel->callid);
1765         }
1766
1767         res = bridge_channel_internal_join(bridge_channel);
1768
1769         /*
1770          * cleanup
1771          *
1772          * If bridge_channel->swap is not NULL then the join failed.
1773          */
1774         ao2_t_cleanup(bridge_channel->swap, "Bridge complete: Departable impart join failed");
1775         bridge_channel->swap = NULL;
1776         ast_bridge_features_destroy(bridge_channel->features);
1777         bridge_channel->features = NULL;
1778
1779         ast_bridge_discard_after_callback(bridge_channel->chan,
1780                 res ? AST_BRIDGE_AFTER_CB_REASON_IMPART_FAILED : AST_BRIDGE_AFTER_CB_REASON_DEPART);
1781         /* If join failed there will be impart threads waiting. */
1782         bridge_channel_impart_signal(bridge_channel->chan);
1783         ast_bridge_discard_after_goto(bridge_channel->chan);
1784
1785         return NULL;
1786 }
1787
1788 /*! \brief Thread responsible for independent imparted bridged channels */
1789 static void *bridge_channel_ind_thread(void *data)
1790 {
1791         struct ast_bridge_channel *bridge_channel = data;
1792         struct ast_channel *chan;
1793
1794         if (bridge_channel->callid) {
1795                 ast_callid_threadassoc_add(bridge_channel->callid);
1796         }
1797
1798         bridge_channel_internal_join(bridge_channel);
1799         chan = bridge_channel->chan;
1800
1801         /* cleanup */
1802         ast_channel_lock(chan);
1803         ast_channel_internal_bridge_channel_set(chan, NULL);
1804         ast_channel_unlock(chan);
1805         bridge_channel->chan = NULL;
1806         /* If bridge_channel->swap is not NULL then the join failed. */
1807         ao2_t_cleanup(bridge_channel->swap, "Bridge complete: Independent impart join failed");
1808         bridge_channel->swap = NULL;
1809         ast_bridge_features_destroy(bridge_channel->features);
1810         bridge_channel->features = NULL;
1811
1812         ao2_ref(bridge_channel, -1);
1813
1814         ast_bridge_run_after_callback(chan);
1815         /* If join failed there will be impart threads waiting. */
1816         bridge_channel_impart_signal(chan);
1817         ast_bridge_run_after_goto(chan);
1818         return NULL;
1819 }
1820
1821 static int bridge_impart_internal(struct ast_bridge *bridge,
1822         struct ast_channel *chan,
1823         struct ast_channel *swap,
1824         struct ast_bridge_features *features,
1825         enum ast_bridge_impart_flags flags,
1826         struct bridge_channel_impart_cond *cond)
1827 {
1828         int res = 0;
1829         struct ast_bridge_channel *bridge_channel;
1830
1831         /* Imparted channels cannot have a PBX. */
1832         if (ast_channel_pbx(chan)) {
1833                 ast_log(AST_LOG_WARNING, "Channel %s has a PBX thread and cannot be imparted into bridge %s\n",
1834                         ast_channel_name(chan), bridge->uniqueid);
1835                 ast_bridge_features_destroy(features);
1836                 return -1;
1837         }
1838
1839         /* Supply an empty features structure if the caller did not. */
1840         if (!features) {
1841                 features = ast_bridge_features_new();
1842                 if (!features) {
1843                         return -1;
1844                 }
1845         }
1846
1847         /* Try to allocate a structure for the bridge channel */
1848         bridge_channel = bridge_channel_internal_alloc(bridge);
1849         if (!bridge_channel) {
1850                 ast_bridge_features_destroy(features);
1851                 return -1;
1852         }
1853
1854         ast_channel_lock(chan);
1855         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE)) {
1856                 ast_log(AST_LOG_NOTICE, "Channel %s is a zombie and cannot be imparted into bridge %s\n",
1857                         ast_channel_name(chan), bridge->uniqueid);
1858                 res = -1;
1859         } else {
1860                 ast_channel_internal_bridge_channel_set(chan, bridge_channel);
1861         }
1862         ast_channel_unlock(chan);
1863         bridge_channel->chan = chan;
1864         bridge_channel->swap = ao2_t_bump(swap, "Setting up bridge impart");
1865         bridge_channel->features = features;
1866         bridge_channel->inhibit_colp = !!(flags & AST_BRIDGE_IMPART_INHIBIT_JOIN_COLP);
1867         bridge_channel->depart_wait =
1868                 (flags & AST_BRIDGE_IMPART_CHAN_MASK) == AST_BRIDGE_IMPART_CHAN_DEPARTABLE;
1869         bridge_channel->callid = ast_read_threadstorage_callid();
1870
1871         /* allow subclass to peek at swap channel before it can hangup */
1872         if (bridge->v_table->push_peek && !res) {
1873                 struct ast_bridge_channel *bcswap = NULL;
1874
1875                 ast_bridge_lock(bridge);
1876                 if (bridge_channel->swap) {
1877                         bcswap = bridge_find_channel(bridge, bridge_channel->swap);
1878                 }
1879                 res = bridge->v_table->push_peek(bridge, bridge_channel, bcswap);
1880                 ast_bridge_unlock(bridge);
1881         }
1882
1883         /* Actually create the thread that will handle the channel */
1884         if (!res) {
1885                 res = bridge_channel_impart_add(chan, cond);
1886         }
1887         if (!res) {
1888                 if ((flags & AST_BRIDGE_IMPART_CHAN_MASK) == AST_BRIDGE_IMPART_CHAN_INDEPENDENT) {
1889                         res = ast_pthread_create_detached(&bridge_channel->thread, NULL,
1890                                 bridge_channel_ind_thread, bridge_channel);
1891                 } else {
1892                         res = ast_pthread_create(&bridge_channel->thread, NULL,
1893                                 bridge_channel_depart_thread, bridge_channel);
1894                 }
1895
1896                 if (!res) {
1897                         bridge_channel_impart_wait(cond);
1898                 }
1899         }
1900
1901         if (res) {
1902                 /* cleanup */
1903                 ast_channel_lock(chan);
1904                 ast_channel_internal_bridge_channel_set(chan, NULL);
1905                 ast_channel_unlock(chan);
1906                 bridge_channel->chan = NULL;
1907                 ao2_t_cleanup(bridge_channel->swap, "Bridge complete: Impart failed");
1908                 bridge_channel->swap = NULL;
1909                 ast_bridge_features_destroy(bridge_channel->features);
1910                 bridge_channel->features = NULL;
1911
1912                 ao2_ref(bridge_channel, -1);
1913                 return -1;
1914         }
1915
1916         return 0;
1917 }
1918
1919 int ast_bridge_impart(struct ast_bridge *bridge,
1920         struct ast_channel *chan,
1921         struct ast_channel *swap,
1922         struct ast_bridge_features *features,
1923         enum ast_bridge_impart_flags flags)
1924 {
1925         struct bridge_channel_impart_cond cond = {
1926                 .done = 0,
1927         };
1928         int res;
1929
1930         ast_mutex_init(&cond.lock);
1931         ast_cond_init(&cond.cond, NULL);
1932
1933         res = bridge_impart_internal(bridge, chan, swap, features, flags, &cond);
1934         if (res) {
1935                 /* Impart failed.  Signal any other waiting impart threads */
1936                 bridge_channel_impart_signal(chan);
1937         }
1938
1939         ast_cond_destroy(&cond.cond);
1940         ast_mutex_destroy(&cond.lock);
1941
1942         return res;
1943 }
1944
1945 int ast_bridge_depart(struct ast_channel *chan)
1946 {
1947         struct ast_bridge_channel *bridge_channel;
1948         int departable;
1949
1950         ast_channel_lock(chan);
1951         bridge_channel = ast_channel_internal_bridge_channel(chan);
1952         departable = bridge_channel && bridge_channel->depart_wait;
1953         ast_channel_unlock(chan);
1954         if (!departable) {
1955                 ast_log(LOG_ERROR, "Channel %s cannot be departed.\n",
1956                         ast_channel_name(chan));
1957                 /*
1958                  * Should never happen.  It likely means that
1959                  * ast_bridge_depart() is called by two threads for the same
1960                  * channel, the channel was never imparted to be departed, or it
1961                  * has already been departed.
1962                  */
1963                 ast_assert(0);
1964                 return -1;
1965         }
1966
1967         /*
1968          * We are claiming the bridge_channel reference held by
1969          * bridge_channel_depart_thread().
1970          */
1971
1972         ast_bridge_channel_leave_bridge(bridge_channel,
1973                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
1974
1975         /* Wait for the depart thread to die */
1976         ast_debug(1, "Waiting for %p(%s) bridge thread to die.\n",
1977                 bridge_channel, ast_channel_name(bridge_channel->chan));
1978         pthread_join(bridge_channel->thread, NULL);
1979
1980         ast_channel_lock(chan);
1981         ast_channel_internal_bridge_channel_set(chan, NULL);
1982         ast_channel_unlock(chan);
1983
1984         /* We can get rid of the bridge_channel after the depart thread has died. */
1985         ao2_ref(bridge_channel, -1);
1986         return 0;
1987 }
1988
1989 int ast_bridge_remove(struct ast_bridge *bridge, struct ast_channel *chan)
1990 {
1991         struct ast_bridge_channel *bridge_channel;
1992
1993         ast_bridge_lock(bridge);
1994
1995         /* Try to find the channel that we want to remove */
1996         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
1997                 ast_bridge_unlock(bridge);
1998                 return -1;
1999         }
2000
2001         ast_bridge_channel_leave_bridge(bridge_channel,
2002                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
2003
2004         ast_bridge_unlock(bridge);
2005
2006         return 0;
2007 }
2008
2009 static void kick_it(struct ast_bridge_channel *bridge_channel, const void *payload, size_t payload_size)
2010 {
2011         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
2012 }
2013
2014 int ast_bridge_kick(struct ast_bridge *bridge, struct ast_channel *chan)
2015 {
2016         struct ast_bridge_channel *bridge_channel;
2017         int res;
2018
2019         ast_bridge_lock(bridge);
2020
2021         /* Try to find the channel that we want to kick. */
2022         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
2023                 ast_bridge_unlock(bridge);
2024                 return -1;
2025         }
2026
2027         res = ast_bridge_channel_queue_callback(bridge_channel, 0, kick_it, NULL, 0);
2028
2029         ast_bridge_unlock(bridge);
2030
2031         return res;
2032 }
2033
2034 /*!
2035  * \internal
2036  * \brief Point the bridge_channel to a new bridge.
2037  * \since 12.0.0
2038  *
2039  * \param bridge_channel What is to point to a new bridge.
2040  * \param new_bridge Where the bridge channel should point.
2041  *
2042  * \return Nothing
2043  */
2044 static void bridge_channel_change_bridge(struct ast_bridge_channel *bridge_channel, struct ast_bridge *new_bridge)
2045 {
2046         struct ast_bridge *old_bridge;
2047
2048         ao2_ref(new_bridge, +1);
2049         ast_bridge_channel_lock(bridge_channel);
2050         ast_channel_lock(bridge_channel->chan);
2051         old_bridge = bridge_channel->bridge;
2052         bridge_channel->bridge = new_bridge;
2053         ast_channel_internal_bridge_set(bridge_channel->chan, new_bridge);
2054         ast_channel_unlock(bridge_channel->chan);
2055         ast_bridge_channel_unlock(bridge_channel);
2056         ao2_ref(old_bridge, -1);
2057 }
2058
2059 static void bridge_channel_moving(struct ast_bridge_channel *bridge_channel, struct ast_bridge *src, struct ast_bridge *dst)
2060 {
2061         struct ast_bridge_features *features = bridge_channel->features;
2062         struct ast_bridge_hook *hook;
2063         struct ao2_iterator iter;
2064
2065         /* Run any moving hooks. */
2066         iter = ao2_iterator_init(features->other_hooks, 0);
2067         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
2068                 int remove_me;
2069                 ast_bridge_move_indicate_callback move_cb;
2070
2071                 if (hook->type != AST_BRIDGE_HOOK_TYPE_MOVE) {
2072                         continue;
2073                 }
2074                 move_cb = (ast_bridge_move_indicate_callback) hook->callback;
2075                 remove_me = move_cb(bridge_channel, hook->hook_pvt, src, dst);
2076                 if (remove_me) {
2077                         ast_debug(1, "Move detection hook %p is being removed from %p(%s)\n",
2078                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
2079                         ao2_unlink(features->other_hooks, hook);
2080                 }
2081         }
2082         ao2_iterator_destroy(&iter);
2083 }
2084
2085 void bridge_do_merge(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, struct ast_bridge_channel **kick_me, unsigned int num_kick,
2086         unsigned int optimized)
2087 {
2088         struct ast_bridge_channel *bridge_channel;
2089         unsigned int idx;
2090
2091         ast_debug(1, "Merging bridge %s into bridge %s\n",
2092                 src_bridge->uniqueid, dst_bridge->uniqueid);
2093
2094         ast_bridge_publish_merge(dst_bridge, src_bridge);
2095
2096         /*
2097          * Move channels from src_bridge over to dst_bridge.
2098          *
2099          * We must use AST_LIST_TRAVERSE_SAFE_BEGIN() because
2100          * bridge_channel_internal_pull() alters the list we are traversing.
2101          */
2102         AST_LIST_TRAVERSE_SAFE_BEGIN(&src_bridge->channels, bridge_channel, entry) {
2103                 if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2104                         /*
2105                          * The channel is already leaving let it leave normally because
2106                          * pulling it may delete hooks that should run for this channel.
2107                          */
2108                         continue;
2109                 }
2110                 if (ast_test_flag(&bridge_channel->features->feature_flags,
2111                         AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
2112                         continue;
2113                 }
2114
2115                 if (kick_me) {
2116                         for (idx = 0; idx < num_kick; ++idx) {
2117                                 if (bridge_channel == kick_me[idx]) {
2118                                         ast_bridge_channel_leave_bridge(bridge_channel,
2119                                                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
2120                                         break;
2121                                 }
2122                         }
2123                 }
2124                 bridge_channel_internal_pull(bridge_channel);
2125                 if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2126                         /*
2127                          * The channel died as a result of being pulled or it was
2128                          * kicked.  Leave it pointing to the original bridge.
2129                          */
2130                         continue;
2131                 }
2132
2133                 bridge_channel_moving(bridge_channel, bridge_channel->bridge, dst_bridge);
2134
2135                 /* Point to new bridge.*/
2136                 bridge_channel_change_bridge(bridge_channel, dst_bridge);
2137
2138                 if (bridge_channel_internal_push(bridge_channel)) {
2139                         ast_bridge_features_remove(bridge_channel->features,
2140                                 AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2141                         ast_bridge_channel_leave_bridge(bridge_channel,
2142                                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
2143                 }
2144         }
2145         AST_LIST_TRAVERSE_SAFE_END;
2146
2147         if (kick_me) {
2148                 /*
2149                  * Now we can kick any channels in the dst_bridge without
2150                  * potentially dissolving the bridge.
2151                  */
2152                 for (idx = 0; idx < num_kick; ++idx) {
2153                         bridge_channel = kick_me[idx];
2154                         ast_bridge_channel_lock(bridge_channel);
2155                         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2156                                 ast_bridge_channel_leave_bridge_nolock(bridge_channel,
2157                                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
2158                                 bridge_channel_internal_pull(bridge_channel);
2159                         }
2160                         ast_bridge_channel_unlock(bridge_channel);
2161                 }
2162         }
2163
2164         bridge_reconfigured(dst_bridge, !optimized);
2165         bridge_reconfigured(src_bridge, !optimized);
2166
2167         ast_debug(1, "Merged bridge %s into bridge %s\n",
2168                 src_bridge->uniqueid, dst_bridge->uniqueid);
2169 }
2170
2171 struct merge_direction {
2172         /*! Destination merge bridge. */
2173         struct ast_bridge *dest;
2174         /*! Source merge bridge. */
2175         struct ast_bridge *src;
2176 };
2177
2178 /*!
2179  * \internal
2180  * \brief Determine which bridge should merge into the other.
2181  * \since 12.0.0
2182  *
2183  * \param bridge1 A bridge for merging
2184  * \param bridge2 A bridge for merging
2185  *
2186  * \note The two bridges are assumed already locked.
2187  *
2188  * \return Which bridge merges into which or NULL bridges if cannot merge.
2189  */
2190 static struct merge_direction bridge_merge_determine_direction(struct ast_bridge *bridge1, struct ast_bridge *bridge2)
2191 {
2192         struct merge_direction merge = { NULL, NULL };
2193         int bridge1_priority;
2194         int bridge2_priority;
2195
2196         if (!ast_test_flag(&bridge1->feature_flags,
2197                         AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)
2198                 && !ast_test_flag(&bridge2->feature_flags,
2199                         AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
2200                 /*
2201                  * Can merge either way.  Merge to the higher priority merge
2202                  * bridge.  Otherwise merge to the larger bridge.
2203                  */
2204                 bridge1_priority = bridge1->v_table->get_merge_priority(bridge1);
2205                 bridge2_priority = bridge2->v_table->get_merge_priority(bridge2);
2206                 if (bridge2_priority < bridge1_priority) {
2207                         merge.dest = bridge1;
2208                         merge.src = bridge2;
2209                 } else if (bridge1_priority < bridge2_priority) {
2210                         merge.dest = bridge2;
2211                         merge.src = bridge1;
2212                 } else {
2213                         /* Merge to the larger bridge. */
2214                         if (bridge2->num_channels <= bridge1->num_channels) {
2215                                 merge.dest = bridge1;
2216                                 merge.src = bridge2;
2217                         } else {
2218                                 merge.dest = bridge2;
2219                                 merge.src = bridge1;
2220                         }
2221                 }
2222         } else if (!ast_test_flag(&bridge1->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
2223                 && !ast_test_flag(&bridge2->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
2224                 /* Can merge only one way. */
2225                 merge.dest = bridge1;
2226                 merge.src = bridge2;
2227         } else if (!ast_test_flag(&bridge2->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
2228                 && !ast_test_flag(&bridge1->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
2229                 /* Can merge only one way. */
2230                 merge.dest = bridge2;
2231                 merge.src = bridge1;
2232         }
2233
2234         return merge;
2235 }
2236
2237 /*!
2238  * \internal
2239  * \brief Merge two bridges together
2240  * \since 12.0.0
2241  *
2242  * \param dst_bridge Destination bridge of merge.
2243  * \param src_bridge Source bridge of merge.
2244  * \param merge_best_direction TRUE if don't care about which bridge merges into the other.
2245  * \param kick_me Array of channels to kick from the bridges.
2246  * \param num_kick Number of channels in the kick_me array.
2247  *
2248  * \note The dst_bridge and src_bridge are assumed already locked.
2249  *
2250  * \retval 0 on success
2251  * \retval -1 on failure
2252  */
2253 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)
2254 {
2255         struct merge_direction merge;
2256         struct ast_bridge_channel **kick_them = NULL;
2257
2258         /* Sanity check. */
2259         ast_assert(dst_bridge && src_bridge && dst_bridge != src_bridge && (!num_kick || kick_me));
2260
2261         if (dst_bridge->dissolved || src_bridge->dissolved) {
2262                 ast_debug(1, "Can't merge bridges %s and %s, at least one bridge is dissolved.\n",
2263                         src_bridge->uniqueid, dst_bridge->uniqueid);
2264                 return -1;
2265         }
2266         if (ast_test_flag(&dst_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)
2267                 || ast_test_flag(&src_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
2268                 ast_debug(1, "Can't merge bridges %s and %s, masquerade only.\n",
2269                         src_bridge->uniqueid, dst_bridge->uniqueid);
2270                 return -1;
2271         }
2272         if (dst_bridge->inhibit_merge || src_bridge->inhibit_merge) {
2273                 ast_debug(1, "Can't merge bridges %s and %s, merging temporarily inhibited.\n",
2274                         src_bridge->uniqueid, dst_bridge->uniqueid);
2275                 return -1;
2276         }
2277
2278         if (merge_best_direction) {
2279                 merge = bridge_merge_determine_direction(dst_bridge, src_bridge);
2280         } else {
2281                 merge.dest = dst_bridge;
2282                 merge.src = src_bridge;
2283         }
2284
2285         if (!merge.dest
2286                 || ast_test_flag(&merge.dest->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
2287                 || ast_test_flag(&merge.src->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
2288                 ast_debug(1, "Can't merge bridges %s and %s, merging inhibited.\n",
2289                         src_bridge->uniqueid, dst_bridge->uniqueid);
2290                 return -1;
2291         }
2292         if (merge.src->num_channels < 2) {
2293                 /*
2294                  * For a two party bridge, a channel may be temporarily removed
2295                  * from the source bridge or the initial bridge members have not
2296                  * joined yet.
2297                  */
2298                 ast_debug(1, "Can't merge bridge %s into bridge %s, not enough channels in source bridge.\n",
2299                         merge.src->uniqueid, merge.dest->uniqueid);
2300                 return -1;
2301         }
2302         if (2 + num_kick < merge.dest->num_channels + merge.src->num_channels
2303                 && !(merge.dest->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)
2304                 && (!ast_test_flag(&merge.dest->feature_flags, AST_BRIDGE_FLAG_SMART)
2305                         || !(merge.dest->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX))) {
2306                 ast_debug(1, "Can't merge bridge %s into bridge %s, multimix is needed and it cannot be acquired.\n",
2307                         merge.src->uniqueid, merge.dest->uniqueid);
2308                 return -1;
2309         }
2310
2311         if (num_kick) {
2312                 unsigned int num_to_kick = 0;
2313                 unsigned int idx;
2314
2315                 kick_them = ast_alloca(num_kick * sizeof(*kick_them));
2316                 for (idx = 0; idx < num_kick; ++idx) {
2317                         kick_them[num_to_kick] = bridge_find_channel(merge.src, kick_me[idx]);
2318                         if (!kick_them[num_to_kick]) {
2319                                 kick_them[num_to_kick] = bridge_find_channel(merge.dest, kick_me[idx]);
2320                         }
2321                         if (kick_them[num_to_kick]) {
2322                                 ++num_to_kick;
2323                         }
2324                 }
2325
2326                 if (num_to_kick != num_kick) {
2327                         ast_debug(1, "Can't merge bridge %s into bridge %s, at least one kicked channel is not in either bridge.\n",
2328                                 merge.src->uniqueid, merge.dest->uniqueid);
2329                         return -1;
2330                 }
2331         }
2332
2333         bridge_do_merge(merge.dest, merge.src, kick_them, num_kick, 0);
2334         return 0;
2335 }
2336
2337 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)
2338 {
2339         int res;
2340
2341         /* Sanity check. */
2342         ast_assert(dst_bridge && src_bridge);
2343
2344         ast_bridge_lock_both(dst_bridge, src_bridge);
2345         res = bridge_merge_locked(dst_bridge, src_bridge, merge_best_direction, kick_me, num_kick);
2346         ast_bridge_unlock(src_bridge);
2347         ast_bridge_unlock(dst_bridge);
2348         return res;
2349 }
2350
2351 int bridge_do_move(struct ast_bridge *dst_bridge, struct ast_bridge_channel *bridge_channel, int attempt_recovery,
2352         unsigned int optimized)
2353 {
2354         struct ast_bridge *orig_bridge;
2355         int was_in_bridge;
2356         int res = 0;
2357
2358         if (bridge_channel->swap) {
2359                 ast_debug(1, "Moving %p(%s) into bridge %s swapping with %s\n",
2360                         bridge_channel, ast_channel_name(bridge_channel->chan), dst_bridge->uniqueid,
2361                         ast_channel_name(bridge_channel->swap));
2362         } else {
2363                 ast_debug(1, "Moving %p(%s) into bridge %s\n",
2364                         bridge_channel, ast_channel_name(bridge_channel->chan), dst_bridge->uniqueid);
2365         }
2366
2367         orig_bridge = bridge_channel->bridge;
2368         was_in_bridge = bridge_channel->in_bridge;
2369
2370         bridge_channel_internal_pull(bridge_channel);
2371         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2372                 /*
2373                  * The channel died as a result of being pulled.  Leave it
2374                  * pointing to the original bridge.
2375                  *
2376                  * Clear out the swap channel pointer.  A ref is not held
2377                  * by bridge_channel->swap at this point.
2378                  */
2379                 bridge_channel->swap = NULL;
2380                 bridge_reconfigured(orig_bridge, 0);
2381                 return -1;
2382         }
2383
2384         /* Point to new bridge.*/
2385         ao2_ref(orig_bridge, +1);/* Keep a ref in case the push fails. */
2386         bridge_channel_change_bridge(bridge_channel, dst_bridge);
2387
2388         bridge_channel_moving(bridge_channel, orig_bridge, dst_bridge);
2389
2390         if (bridge_channel_internal_push_full(bridge_channel, optimized)) {
2391                 /* Try to put the channel back into the original bridge. */
2392                 ast_bridge_features_remove(bridge_channel->features,
2393                         AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2394                 if (attempt_recovery && was_in_bridge) {
2395                         /* Point back to original bridge. */
2396                         bridge_channel_change_bridge(bridge_channel, orig_bridge);
2397
2398                         if (bridge_channel_internal_push(bridge_channel)) {
2399                                 ast_bridge_features_remove(bridge_channel->features,
2400                                         AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2401                                 ast_bridge_channel_leave_bridge(bridge_channel,
2402                                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
2403                         }
2404                 } else {
2405                         ast_bridge_channel_leave_bridge(bridge_channel,
2406                                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
2407                         bridge_channel_settle_owed_events(orig_bridge, bridge_channel);
2408                 }
2409                 res = -1;
2410         } else if (!optimized) {
2411                 bridge_channel_settle_owed_events(orig_bridge, bridge_channel);
2412         }
2413
2414         bridge_reconfigured(dst_bridge, !optimized);
2415         bridge_reconfigured(orig_bridge, !optimized);
2416         ao2_ref(orig_bridge, -1);
2417         return res;
2418 }
2419
2420 /*!
2421  * \internal
2422  * \brief Move a channel from one bridge to another.
2423  * \since 12.0.0
2424  *
2425  * \param dst_bridge Destination bridge of bridge channel move.
2426  * \param src_bridge Source bridge of bridge channel move.
2427  * \param chan Channel to move.
2428  * \param swap Channel to replace in dst_bridge.
2429  * \param attempt_recovery TRUE if failure attempts to push channel back into original bridge.
2430  *
2431  * \note The dst_bridge and src_bridge are assumed already locked.
2432  *
2433  * \retval 0 on success.
2434  * \retval -1 on failure.
2435  */
2436 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)
2437 {
2438         struct ast_bridge_channel *bridge_channel;
2439
2440         if (dst_bridge->dissolved || src_bridge->dissolved) {
2441                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, at least one bridge is dissolved.\n",
2442                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2443                 return -1;
2444         }
2445         if (ast_test_flag(&dst_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)
2446                 || ast_test_flag(&src_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
2447                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, masquerade only.\n",
2448                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2449                 return -1;
2450         }
2451         if (dst_bridge->inhibit_merge || src_bridge->inhibit_merge) {
2452                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, temporarily inhibited.\n",
2453                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2454                 return -1;
2455         }
2456
2457         bridge_channel = bridge_find_channel(src_bridge, chan);
2458         if (!bridge_channel) {
2459                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel not in bridge.\n",
2460                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2461                 return -1;
2462         }
2463         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2464                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel leaving bridge.\n",
2465                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2466                 return -1;
2467         }
2468         if (ast_test_flag(&bridge_channel->features->feature_flags,
2469                 AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
2470                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel immovable.\n",
2471                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2472                 return -1;
2473         }
2474
2475         if (swap) {
2476                 struct ast_bridge_channel *bridge_channel_swap;
2477
2478                 bridge_channel_swap = bridge_find_channel(dst_bridge, swap);
2479                 if (!bridge_channel_swap) {
2480                         ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, swap channel %s not in bridge.\n",
2481                                 ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid,
2482                                 ast_channel_name(swap));
2483                         return -1;
2484                 }
2485                 if (bridge_channel_swap->state != BRIDGE_CHANNEL_STATE_WAIT) {
2486                         ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, swap channel %s leaving bridge.\n",
2487                                 ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid,
2488                                 ast_channel_name(swap));
2489                         return -1;
2490                 }
2491         }
2492
2493         bridge_channel->swap = swap;
2494         return bridge_do_move(dst_bridge, bridge_channel, attempt_recovery, 0);
2495 }
2496
2497 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)
2498 {
2499         int res;
2500
2501         ast_bridge_lock_both(dst_bridge, src_bridge);
2502         res = bridge_move_locked(dst_bridge, src_bridge, chan, swap, attempt_recovery);
2503         ast_bridge_unlock(src_bridge);
2504         ast_bridge_unlock(dst_bridge);
2505         return res;
2506 }
2507
2508 int ast_bridge_add_channel(struct ast_bridge *bridge, struct ast_channel *chan,
2509         struct ast_bridge_features *features, int play_tone, const char *xfersound)
2510 {
2511         RAII_VAR(struct ast_bridge *, chan_bridge, NULL, ao2_cleanup);
2512         RAII_VAR(struct ast_channel *, yanked_chan, NULL, ao2_cleanup);
2513
2514         ast_moh_stop(chan);
2515
2516         ast_channel_lock(chan);
2517         chan_bridge = ast_channel_get_bridge(chan);
2518         ast_channel_unlock(chan);
2519
2520         if (chan_bridge) {
2521                 struct ast_bridge_channel *bridge_channel;
2522
2523                 /* The channel is in a bridge so it is not getting any new features. */
2524                 ast_bridge_features_destroy(features);
2525
2526                 ast_bridge_lock_both(bridge, chan_bridge);
2527                 bridge_channel = bridge_find_channel(chan_bridge, chan);
2528
2529                 if (bridge_move_locked(bridge, chan_bridge, chan, NULL, 1)) {
2530                         ast_bridge_unlock(chan_bridge);
2531                         ast_bridge_unlock(bridge);
2532                         return -1;
2533                 }
2534
2535                 /*
2536                  * bridge_move_locked() will implicitly ensure that
2537                  * bridge_channel is not NULL.
2538                  */
2539                 ast_assert(bridge_channel != NULL);
2540
2541                 /*
2542                  * Additional checks if the channel we just stole dissolves the
2543                  * original bridge.
2544                  */
2545                 bridge_dissolve_check_stolen(chan_bridge, bridge_channel);
2546                 ast_bridge_unlock(chan_bridge);
2547                 ast_bridge_unlock(bridge);
2548         } else {
2549                 /* Slightly less easy case. We need to yank channel A from
2550                  * where he currently is and impart him into our bridge.
2551                  */
2552                 yanked_chan = ast_channel_yank(chan);
2553                 if (!yanked_chan) {
2554                         ast_log(LOG_WARNING, "Could not gain control of channel %s\n", ast_channel_name(chan));
2555                         ast_bridge_features_destroy(features);
2556                         return -1;
2557                 }
2558                 if (ast_channel_state(yanked_chan) != AST_STATE_UP) {
2559                         ast_answer(yanked_chan);
2560                 }
2561                 ast_channel_ref(yanked_chan);
2562                 if (ast_bridge_impart(bridge, yanked_chan, NULL, features,
2563                         AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
2564                         /* It is possible for us to yank a channel and have some other
2565                          * thread start a PBX on the channl after we yanked it. In particular,
2566                          * this can theoretically happen on the ;2 of a Local channel if we
2567                          * yank it prior to the ;1 being answered. Make sure that it isn't
2568                          * executing a PBX before hanging it up.
2569                          */
2570                         if (ast_channel_pbx(yanked_chan)) {
2571                                 ast_channel_unref(yanked_chan);
2572                         } else {
2573                                 ast_hangup(yanked_chan);
2574                         }
2575                         return -1;
2576                 }
2577         }
2578
2579         if (play_tone && !ast_strlen_zero(xfersound)) {
2580                 struct ast_channel *play_chan = yanked_chan ?: chan;
2581                 RAII_VAR(struct ast_bridge_channel *, play_bridge_channel, NULL, ao2_cleanup);
2582
2583                 ast_channel_lock(play_chan);
2584                 play_bridge_channel = ast_channel_get_bridge_channel(play_chan);
2585                 ast_channel_unlock(play_chan);
2586
2587                 if (!play_bridge_channel) {
2588                         ast_log(LOG_WARNING, "Unable to play tone for channel %s. No longer in a bridge.\n",
2589                                 ast_channel_name(play_chan));
2590                 } else {
2591                         ast_bridge_channel_queue_playfile(play_bridge_channel, NULL, xfersound, NULL);
2592                 }
2593         }
2594         return 0;
2595 }
2596
2597 static int bridge_allows_optimization(struct ast_bridge *bridge)
2598 {
2599         return !(bridge->inhibit_merge
2600                 || bridge->dissolved
2601                 || ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY));
2602 }
2603
2604 /*!
2605  * \internal
2606  * \brief Lock the unreal channel stack for chan and prequalify it.
2607  * \since 12.0.0
2608  *
2609  * \param chan Unreal channel writing a frame into the channel driver.
2610  *
2611  * \note It is assumed that chan is already locked.
2612  *
2613  * \retval bridge on success with bridge and bridge_channel locked.
2614  * \retval NULL if cannot do optimization now.
2615  */
2616 static struct ast_bridge *optimize_lock_chan_stack(struct ast_channel *chan)
2617 {
2618         struct ast_bridge *bridge;
2619         struct ast_bridge_channel *bridge_channel;
2620
2621         if (!AST_LIST_EMPTY(ast_channel_readq(chan))) {
2622                 return NULL;
2623         }
2624         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF)) {
2625                 return NULL;
2626         }
2627         if (ast_channel_has_audio_frame_or_monitor(chan)) {
2628                 /* Channel has an active monitor, audiohook, or framehook. */
2629                 return NULL;
2630         }
2631         bridge_channel = ast_channel_internal_bridge_channel(chan);
2632         if (!bridge_channel || ast_bridge_channel_trylock(bridge_channel)) {
2633                 return NULL;
2634         }
2635         bridge = bridge_channel->bridge;
2636         if (bridge_channel->activity != BRIDGE_CHANNEL_THREAD_SIMPLE
2637                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2638                 || ast_bridge_trylock(bridge)) {
2639                 ast_bridge_channel_unlock(bridge_channel);
2640                 return NULL;
2641         }
2642         if (!bridge_channel_internal_allows_optimization(bridge_channel) ||
2643                         !bridge_allows_optimization(bridge)) {
2644                 ast_bridge_unlock(bridge);
2645                 ast_bridge_channel_unlock(bridge_channel);
2646                 return NULL;
2647         }
2648         return bridge;
2649 }
2650
2651 /*!
2652  * \internal
2653  * \brief Lock the unreal channel stack for peer and prequalify it.
2654  * \since 12.0.0
2655  *
2656  * \param peer Other unreal channel in the pair.
2657  *
2658  * \retval bridge on success with bridge, bridge_channel, and peer locked.
2659  * \retval NULL if cannot do optimization now.
2660  */
2661 static struct ast_bridge *optimize_lock_peer_stack(struct ast_channel *peer)
2662 {
2663         struct ast_bridge *bridge;
2664         struct ast_bridge_channel *bridge_channel;
2665
2666         if (ast_channel_trylock(peer)) {
2667                 return NULL;
2668         }
2669         if (!AST_LIST_EMPTY(ast_channel_readq(peer))) {
2670                 ast_channel_unlock(peer);
2671                 return NULL;
2672         }
2673         if (ast_test_flag(ast_channel_flags(peer), AST_FLAG_EMULATE_DTMF)) {
2674                 ast_channel_unlock(peer);
2675                 return NULL;
2676         }
2677         if (ast_channel_has_audio_frame_or_monitor(peer)) {
2678                 /* Peer has an active monitor, audiohook, or framehook. */
2679                 ast_channel_unlock(peer);
2680                 return NULL;
2681         }
2682         bridge_channel = ast_channel_internal_bridge_channel(peer);
2683         if (!bridge_channel || ast_bridge_channel_trylock(bridge_channel)) {
2684                 ast_channel_unlock(peer);
2685                 return NULL;
2686         }
2687         bridge = bridge_channel->bridge;
2688         if (bridge_channel->activity != BRIDGE_CHANNEL_THREAD_IDLE
2689                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2690                 || ast_bridge_trylock(bridge)) {
2691                 ast_bridge_channel_unlock(bridge_channel);
2692                 ast_channel_unlock(peer);
2693                 return NULL;
2694         }
2695         if (!bridge_allows_optimization(bridge) ||
2696                         !bridge_channel_internal_allows_optimization(bridge_channel)) {
2697                 ast_bridge_unlock(bridge);
2698                 ast_bridge_channel_unlock(bridge_channel);
2699                 ast_channel_unlock(peer);
2700                 return NULL;
2701         }
2702         return bridge;
2703 }
2704
2705 /*!
2706  * \internal
2707  * \brief Indicates allowability of a swap optimization
2708  */
2709 enum bridge_allow_swap {
2710         /*! Bridges cannot allow for a swap optimization to occur */
2711         SWAP_PROHIBITED,
2712         /*! Bridge swap optimization can occur into the chan_bridge */
2713         SWAP_TO_CHAN_BRIDGE,
2714         /*! Bridge swap optimization can occur into the peer_bridge */
2715         SWAP_TO_PEER_BRIDGE,
2716 };
2717
2718 /*!
2719  * \internal
2720  * \brief Determine if two bridges allow for swap optimization to occur
2721  *
2722  * \param chan_bridge First bridge being tested
2723  * \param peer_bridge Second bridge being tested
2724  * \return Allowability of swap optimization
2725  */
2726 static enum bridge_allow_swap bridges_allow_swap_optimization(struct ast_bridge *chan_bridge,
2727                 struct ast_bridge *peer_bridge)
2728 {
2729         int chan_priority;
2730         int peer_priority;
2731
2732         if (!ast_test_flag(&chan_bridge->feature_flags,
2733                         AST_BRIDGE_FLAG_SWAP_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM |
2734                         AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2735                 && !ast_test_flag(&peer_bridge->feature_flags,
2736                         AST_BRIDGE_FLAG_SWAP_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM |
2737                         AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)) {
2738                 /*
2739                  * Can swap either way.  Swap to the higher priority merge
2740                  * bridge.
2741                  */
2742                 chan_priority = chan_bridge->v_table->get_merge_priority(chan_bridge);
2743                 peer_priority = peer_bridge->v_table->get_merge_priority(peer_bridge);
2744                 if (chan_bridge->num_channels == 2
2745                         && chan_priority <= peer_priority) {
2746                         return SWAP_TO_PEER_BRIDGE;
2747                 } else if (peer_bridge->num_channels == 2
2748                         && peer_priority <= chan_priority) {
2749                         return SWAP_TO_CHAN_BRIDGE;
2750                 }
2751         } else if (chan_bridge->num_channels == 2
2752                 && !ast_test_flag(&chan_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM | AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2753                 && !ast_test_flag(&peer_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_TO)) {
2754                 /* Can swap optimize only one way. */
2755                 return SWAP_TO_PEER_BRIDGE;
2756         } else if (peer_bridge->num_channels == 2
2757                 && !ast_test_flag(&peer_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM | AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2758                 && !ast_test_flag(&chan_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_TO)) {
2759                 /* Can swap optimize only one way. */
2760                 return SWAP_TO_CHAN_BRIDGE;
2761         }
2762
2763         return SWAP_PROHIBITED;
2764 }
2765
2766 /*!
2767  * \internal
2768  * \brief Check and attempt to swap optimize out the unreal channels.
2769  * \since 12.0.0
2770  *
2771  * \param chan_bridge
2772  * \param chan_bridge_channel
2773  * \param peer_bridge
2774  * \param peer_bridge_channel
2775  * \param pvt Unreal data containing callbacks to call if the optimization actually
2776  * happens
2777  *
2778  * \retval 1 if unreal channels failed to optimize out.
2779  * \retval 0 if unreal channels were not optimized out.
2780  * \retval -1 if unreal channels were optimized out.
2781  */
2782 static int try_swap_optimize_out(struct ast_bridge *chan_bridge,
2783         struct ast_bridge_channel *chan_bridge_channel, struct ast_bridge *peer_bridge,
2784         struct ast_bridge_channel *peer_bridge_channel,
2785         struct ast_unreal_pvt *pvt)
2786 {
2787         struct ast_bridge *dst_bridge;
2788         struct ast_bridge_channel *dst_bridge_channel;
2789         struct ast_bridge_channel *src_bridge_channel;
2790         struct ast_bridge_channel *other;
2791         int res = 1;
2792
2793         switch (bridges_allow_swap_optimization(chan_bridge, peer_bridge)) {
2794         case SWAP_TO_CHAN_BRIDGE:
2795                 dst_bridge = chan_bridge;
2796                 dst_bridge_channel = chan_bridge_channel;
2797                 src_bridge_channel = peer_bridge_channel;
2798                 break;
2799         case SWAP_TO_PEER_BRIDGE:
2800                 dst_bridge = peer_bridge;
2801                 dst_bridge_channel = peer_bridge_channel;
2802                 src_bridge_channel = chan_bridge_channel;
2803                 break;
2804         case SWAP_PROHIBITED:
2805         default:
2806                 return 0;
2807         }
2808
2809         other = ast_bridge_channel_peer(src_bridge_channel);
2810         if (other && other->state == BRIDGE_CHANNEL_STATE_WAIT) {
2811                 unsigned int id;
2812
2813                 if (ast_channel_trylock(other->chan)) {
2814                         return 1;
2815                 }
2816
2817                 id = ast_atomic_fetchadd_int((int *) &optimization_id, +1);
2818
2819                 ast_verb(4, "Move-swap optimizing %s <-- %s.\n",
2820                         ast_channel_name(dst_bridge_channel->chan),
2821                         ast_channel_name(other->chan));
2822
2823                 if (pvt && !ast_test_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN) && pvt->callbacks
2824                                 && pvt->callbacks->optimization_started) {
2825                         pvt->callbacks->optimization_started(pvt, other->chan,
2826                                         dst_bridge_channel->chan == pvt->owner ? AST_UNREAL_OWNER : AST_UNREAL_CHAN,
2827                                         id);
2828                         ast_set_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN);
2829                 }
2830                 other->swap = dst_bridge_channel->chan;
2831                 if (!bridge_do_move(dst_bridge, other, 1, 1)) {
2832                         ast_bridge_channel_leave_bridge(src_bridge_channel,
2833                                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
2834                         res = -1;
2835                 }
2836                 if (pvt && pvt->callbacks && pvt->callbacks->optimization_finished) {
2837                         pvt->callbacks->optimization_finished(pvt, res == 1, id);
2838                 }
2839                 ast_channel_unlock(other->chan);
2840         }
2841         return res;
2842 }
2843
2844 /*!
2845  * \internal
2846  * \brief Indicates allowability of a merge optimization
2847  */
2848 enum bridge_allow_merge {
2849         /*! Bridge properties prohibit merge optimization */
2850         MERGE_PROHIBITED,
2851         /*! Merge optimization cannot occur because the source bridge has too few channels */
2852         MERGE_NOT_ENOUGH_CHANNELS,
2853         /*! Merge optimization cannot occur because multimix capability could not be requested */
2854         MERGE_NO_MULTIMIX,
2855         /*! Merge optimization allowed between bridges */
2856         MERGE_ALLOWED,
2857 };
2858
2859 /*!
2860  * \internal
2861  * \brief Determines allowability of a merge optimization
2862  *
2863  * \note The merge output parameter is undefined if MERGE_PROHIBITED is returned. For success
2864  * and other failure returns, a merge direction was determined, and the parameter is safe to
2865  * access.
2866  *
2867  * \param chan_bridge First bridge being tested
2868  * \param peer_bridge Second bridge being tested
2869  * \param num_kick_channels The number of channels to remove from the bridges during merging
2870  * \param[out] merge Indicates the recommended direction for the bridge merge
2871  */
2872 static enum bridge_allow_merge bridges_allow_merge_optimization(struct ast_bridge *chan_bridge,
2873                 struct ast_bridge *peer_bridge, int num_kick_channels, struct merge_direction *merge)
2874 {
2875         *merge = bridge_merge_determine_direction(chan_bridge, peer_bridge);
2876         if (!merge->dest) {
2877                 return MERGE_PROHIBITED;
2878         }
2879         if (merge->src->num_channels < 2) {
2880                 return MERGE_NOT_ENOUGH_CHANNELS;
2881         } else if ((2 + num_kick_channels) < merge->dest->num_channels + merge->src->num_channels
2882                 && !(merge->dest->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)
2883                 && (!ast_test_flag(&merge->dest->feature_flags, AST_BRIDGE_FLAG_SMART)
2884                         || !(merge->dest->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX))) {
2885                 return MERGE_NO_MULTIMIX;
2886         }
2887
2888         return MERGE_ALLOWED;
2889 }
2890
2891 /*!
2892  * \internal
2893  * \brief Check and attempt to merge optimize out the unreal channels.
2894  * \since 12.0.0
2895  *
2896  * \param chan_bridge
2897  * \param chan_bridge_channel
2898  * \param peer_bridge
2899  * \param peer_bridge_channel
2900  * \param pvt Unreal data containing callbacks to call if the optimization actually
2901  * happens
2902  *
2903  * \retval 0 if unreal channels were not optimized out.
2904  * \retval -1 if unreal channels were optimized out.
2905  */
2906 static int try_merge_optimize_out(struct ast_bridge *chan_bridge,
2907         struct ast_bridge_channel *chan_bridge_channel, struct ast_bridge *peer_bridge,
2908         struct ast_bridge_channel *peer_bridge_channel,
2909         struct ast_unreal_pvt *pvt)
2910 {
2911         struct merge_direction merge;
2912         struct ast_bridge_channel *kick_me[] = {
2913                 chan_bridge_channel,
2914                 peer_bridge_channel,
2915         };
2916         unsigned int id;
2917
2918         switch (bridges_allow_merge_optimization(chan_bridge, peer_bridge, ARRAY_LEN(kick_me), &merge)) {
2919         case MERGE_ALLOWED:
2920                 break;
2921         case MERGE_PROHIBITED:
2922                 return 0;
2923         case MERGE_NOT_ENOUGH_CHANNELS:
2924                 ast_debug(4, "Can't optimize %s -- %s out, not enough channels in bridge %s.\n",
2925                         ast_channel_name(chan_bridge_channel->chan),
2926                         ast_channel_name(peer_bridge_channel->chan),
2927                         merge.src->uniqueid);
2928                 return 0;
2929         case MERGE_NO_MULTIMIX:
2930                 ast_debug(4, "Can't optimize %s -- %s out, multimix is needed and it cannot be acquired.\n",
2931                         ast_channel_name(chan_bridge_channel->chan),
2932                         ast_channel_name(peer_bridge_channel->chan));
2933                 return 0;
2934         }
2935
2936         ast_verb(4, "Merge optimizing %s -- %s out.\n",
2937                 ast_channel_name(chan_bridge_channel->chan),
2938                 ast_channel_name(peer_bridge_channel->chan));
2939
2940         id = ast_atomic_fetchadd_int((int *) &optimization_id, +1);
2941
2942         if (pvt && !ast_test_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN) && pvt->callbacks
2943                         && pvt->callbacks->optimization_started) {
2944                 pvt->callbacks->optimization_started(pvt, NULL,
2945                                 merge.dest == ast_channel_internal_bridge(pvt->owner) ? AST_UNREAL_OWNER : AST_UNREAL_CHAN,
2946                                 id);
2947                 ast_set_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN);
2948         }
2949         bridge_do_merge(merge.dest, merge.src, kick_me, ARRAY_LEN(kick_me), 1);
2950         if (pvt && pvt->callbacks && pvt->callbacks->optimization_finished) {
2951                 pvt->callbacks->optimization_finished(pvt, 1, id);
2952         }
2953
2954         return -1;
2955 }
2956
2957 int ast_bridge_unreal_optimize_out(struct ast_channel *chan, struct ast_channel *peer, struct ast_unreal_pvt *pvt)
2958 {
2959         struct ast_bridge *chan_bridge;
2960         struct ast_bridge *peer_bridge;
2961         struct ast_bridge_channel *chan_bridge_channel;
2962         struct ast_bridge_channel *peer_bridge_channel;
2963         int res = 0;
2964
2965         chan_bridge = optimize_lock_chan_stack(chan);
2966         if (!chan_bridge) {
2967                 return res;
2968         }
2969         chan_bridge_channel = ast_channel_internal_bridge_channel(chan);
2970
2971         peer_bridge = optimize_lock_peer_stack(peer);
2972         if (peer_bridge) {
2973                 peer_bridge_channel = ast_channel_internal_bridge_channel(peer);
2974
2975                 res = try_swap_optimize_out(chan_bridge, chan_bridge_channel,
2976                         peer_bridge, peer_bridge_channel, pvt);
2977                 if (!res) {
2978                         res = try_merge_optimize_out(chan_bridge, chan_bridge_channel,
2979                                 peer_bridge, peer_bridge_channel, pvt);
2980                 } else if (0 < res) {
2981                         res = 0;
2982                 }
2983
2984                 /* Release peer locks. */
2985                 ast_bridge_unlock(peer_bridge);
2986                 ast_bridge_channel_unlock(peer_bridge_channel);
2987                 ast_channel_unlock(peer);
2988         }
2989
2990         /* Release chan locks. */
2991         ast_bridge_unlock(chan_bridge);
2992         ast_bridge_channel_unlock(chan_bridge_channel);
2993
2994         return res;
2995 }
2996
2997 enum ast_bridge_optimization ast_bridges_allow_optimization(struct ast_bridge *chan_bridge,
2998                 struct ast_bridge *peer_bridge)
2999 {
3000         struct merge_direction merge;
3001
3002         if (!bridge_allows_optimization(chan_bridge) || !bridge_allows_optimization(peer_bridge)) {
3003                 return AST_BRIDGE_OPTIMIZE_PROHIBITED;
3004         }
3005
3006         switch (bridges_allow_swap_optimization(chan_bridge, peer_bridge)) {
3007         case SWAP_TO_CHAN_BRIDGE:
3008                 return AST_BRIDGE_OPTIMIZE_SWAP_TO_CHAN_BRIDGE;
3009         case SWAP_TO_PEER_BRIDGE:
3010                 return AST_BRIDGE_OPTIMIZE_SWAP_TO_PEER_BRIDGE;
3011         case SWAP_PROHIBITED:
3012         default:
3013                 break;
3014         }
3015
3016         /* Two channels will be kicked from the bridges, the unreal;1 and unreal;2 channels */
3017         if (bridges_allow_merge_optimization(chan_bridge, peer_bridge, 2, &merge) != MERGE_ALLOWED) {
3018                 return AST_BRIDGE_OPTIMIZE_PROHIBITED;
3019         }
3020
3021         if (merge.dest == chan_bridge) {
3022                 return AST_BRIDGE_OPTIMIZE_MERGE_TO_CHAN_BRIDGE;
3023         } else {
3024                 return AST_BRIDGE_OPTIMIZE_MERGE_TO_PEER_BRIDGE;
3025         }
3026 }
3027
3028 /*!
3029  * \internal
3030  * \brief Adjust the bridge merge inhibit request count.
3031  * \since 12.0.0
3032  *
3033  * \param bridge What to operate on.
3034  * \param request Inhibit request increment.
3035  *     (Positive to add requests.  Negative to remove requests.)
3036  *
3037  * \note This function assumes bridge is locked.
3038  *
3039  * \return Nothing
3040  */
3041 void bridge_merge_inhibit_nolock(struct ast_bridge *bridge, int request)
3042 {
3043         int new_request;
3044
3045         new_request = bridge->inhibit_merge + request;
3046         ast_assert(0 <= new_request);
3047         bridge->inhibit_merge = new_request;
3048 }
3049
3050 void ast_bridge_merge_inhibit(struct ast_bridge *bridge, int request)
3051 {
3052         ast_bridge_lock(bridge);
3053         bridge_merge_inhibit_nolock(bridge, request);
3054         ast_bridge_unlock(bridge);
3055 }
3056
3057 int ast_bridge_suspend(struct ast_bridge *bridge, struct ast_channel *chan)
3058 {
3059         struct ast_bridge_channel *bridge_channel;
3060 /* XXX ASTERISK-21271 the case of a disolved bridge while channel is suspended is not handled. */
3061 /* XXX ASTERISK-21271 suspend/unsuspend needs to be rethought. The caller must block until it has successfully suspended the channel for temporary control. */
3062 /* 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. */
3063
3064         ast_bridge_lock(bridge);
3065
3066         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
3067                 ast_bridge_unlock(bridge);
3068                 return -1;
3069         }
3070
3071         bridge_channel_internal_suspend_nolock(bridge_channel);
3072
3073         ast_bridge_unlock(bridge);
3074
3075         return 0;
3076 }
3077
3078 int ast_bridge_unsuspend(struct ast_bridge *bridge, struct ast_channel *chan)
3079 {
3080         struct ast_bridge_channel *bridge_channel;
3081 /* XXX ASTERISK-21271 the case of a disolved bridge while channel is suspended is not handled. */
3082
3083         ast_bridge_lock(bridge);
3084
3085         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
3086                 ast_bridge_unlock(bridge);
3087                 return -1;
3088         }
3089
3090         bridge_channel_internal_unsuspend_nolock(bridge_channel);
3091
3092         ast_bridge_unlock(bridge);
3093
3094         return 0;
3095 }
3096
3097 void ast_bridge_technology_suspend(struct ast_bridge_technology *technology)
3098 {
3099         technology->suspended = 1;
3100 }
3101
3102 void ast_bridge_technology_unsuspend(struct ast_bridge_technology *technology)
3103 {
3104         /*
3105          * XXX We may want the act of unsuspending a bridge technology
3106          * to prod all existing bridges to see if they should start
3107          * using it.
3108          */
3109         technology->suspended = 0;
3110 }
3111
3112 int ast_bridge_features_register(enum ast_bridge_builtin_feature feature, ast_bridge_hook_callback callback, const char *dtmf)
3113 {
3114         if (ARRAY_LEN(builtin_features_handlers) <= feature
3115                 || builtin_features_handlers[feature]) {
3116                 return -1;
3117         }
3118
3119         if (!ast_strlen_zero(dtmf)) {
3120                 ast_copy_string(builtin_features_dtmf[feature], dtmf, sizeof(builtin_features_dtmf[feature]));
3121         }
3122
3123         builtin_features_handlers[feature] = callback;
3124
3125         return 0;
3126 }
3127
3128 int ast_bridge_features_unregister(enum ast_bridge_builtin_feature feature)
3129 {
3130         if (ARRAY_LEN(builtin_features_handlers) <= feature
3131                 || !builtin_features_handlers[feature]) {
3132                 return -1;
3133         }
3134
3135         builtin_features_handlers[feature] = NULL;
3136
3137         return 0;
3138 }
3139
3140 int ast_bridge_features_do(enum ast_bridge_builtin_feature feature, struct ast_bridge_channel *bridge_channel, void *hook_pvt)
3141 {
3142         ast_bridge_hook_callback callback;
3143
3144         if (ARRAY_LEN(builtin_features_handlers) <= feature) {
3145                 return -1;
3146         }
3147
3148         callback = builtin_features_handlers[feature];
3149         if (!callback) {
3150                 return -1;
3151         }
3152         callback(bridge_channel, hook_pvt);
3153
3154         return 0;
3155 }
3156
3157 int ast_bridge_interval_register(enum ast_bridge_builtin_interval interval, ast_bridge_builtin_set_limits_fn callback)
3158 {
3159         if (ARRAY_LEN(builtin_interval_handlers) <= interval
3160                 || builtin_interval_handlers[interval]) {
3161                 return -1;
3162         }
3163
3164         builtin_interval_handlers[interval] = callback;
3165
3166         return 0;
3167 }
3168
3169 int ast_bridge_interval_unregister(enum ast_bridge_builtin_interval interval)
3170 {
3171         if (ARRAY_LEN(builtin_interval_handlers) <= interval
3172                 || !builtin_interval_handlers[interval]) {
3173                 return -1;
3174         }
3175
3176         builtin_interval_handlers[interval] = NULL;
3177
3178         return 0;
3179
3180 }
3181
3182 /*!
3183  * \internal
3184  * \brief Bridge hook destructor.
3185  * \since 12.0.0
3186  *
3187  * \param vhook Object to destroy.
3188  *
3189  * \return Nothing
3190  */
3191 static void bridge_hook_destroy(void *vhook)
3192 {
3193         struct ast_bridge_hook *hook = vhook;
3194
3195         if (hook->destructor) {
3196                 hook->destructor(hook->hook_pvt);
3197         }
3198 }
3199
3200 /*!
3201  * \internal
3202  * \brief Allocate and setup a generic bridge hook.
3203  * \since 12.0.0
3204  *
3205  * \param size How big an object to allocate.
3206  * \param callback Function to execute upon activation
3207  * \param hook_pvt Unique data
3208  * \param destructor Optional destructor callback for hook_pvt data
3209  * \param remove_flags Dictates what situations the hook should be removed.
3210  *
3211  * \retval hook on success.
3212  * \retval NULL on error.
3213  */
3214 static struct ast_bridge_hook *bridge_hook_generic(size_t size,
3215         ast_bridge_hook_callback callback,
3216         void *hook_pvt,
3217         ast_bridge_hook_pvt_destructor destructor,
3218         enum ast_bridge_hook_remove_flags remove_flags)
3219 {
3220         struct ast_bridge_hook *hook;
3221
3222         /* Allocate new hook and setup it's basic variables */
3223         hook = ao2_alloc_options(size, bridge_hook_destroy, AO2_ALLOC_OPT_LOCK_NOLOCK);
3224         if (hook) {
3225                 hook->callback = callback;
3226                 hook->destructor = destructor;
3227                 hook->hook_pvt = hook_pvt;
3228                 ast_set_flag(&hook->remove_flags, remove_flags);
3229         }
3230
3231         return hook;
3232 }
3233
3234 int ast_bridge_dtmf_hook(struct ast_bridge_features *features,
3235         const char *dtmf,
3236         ast_bridge_hook_callback callback,
3237         void *hook_pvt,
3238         ast_bridge_hook_pvt_destructor destructor,
3239         enum ast_bridge_hook_remove_flags remove_flags)
3240 {
3241         struct ast_bridge_hook_dtmf *hook;
3242         int res;
3243
3244         /* Allocate new hook and setup it's various variables */
3245         hook = (struct ast_bridge_hook_dtmf *) bridge_hook_generic(sizeof(*hook), callback,
3246                 hook_pvt, destructor, remove_flags);
3247         if (!hook) {
3248                 return -1;
3249         }
3250         hook->generic.type = AST_BRIDGE_HOOK_TYPE_DTMF;
3251         ast_copy_string(hook->dtmf.code, dtmf, sizeof(hook->dtmf.code));
3252
3253         /* Once done we put it in the container. */
3254         res = ao2_link(features->dtmf_hooks, hook) ? 0 : -1;
3255         if (res) {
3256                 /*
3257                  * Could not link the hook into the container.
3258                  *
3259                  * Remove the hook_pvt destructor call from the hook since we
3260                  * are returning failure to install the hook.
3261                  */
3262                 hook->generic.destructor = NULL;
3263         }
3264         ao2_ref(hook, -1);
3265
3266         return res;
3267 }
3268
3269 /*!
3270  * \internal
3271  * \brief Attach an other hook to a bridge features structure
3272  *
3273  * \param features Bridge features structure
3274  * \param callback Function to execute upon activation
3275  * \param hook_pvt Unique data
3276  * \param destructor Optional destructor callback for hook_pvt data
3277  * \param remove_flags Dictates what situations the hook should be removed.
3278  * \param type What type of hook is being attached.
3279  *
3280  * \retval 0 on success
3281  * \retval -1 on failure (The caller must cleanup any hook_pvt resources.)
3282  */
3283 static int bridge_other_hook(struct ast_bridge_features *features,
3284         ast_bridge_hook_callback callback,
3285         void *hook_pvt,
3286         ast_bridge_hook_pvt_destructor destructor,
3287         enum ast_bridge_hook_remove_flags remove_flags,
3288         enum ast_bridge_hook_type type)
3289 {
3290         struct ast_bridge_hook *hook;
3291         int res;
3292
3293         /* Allocate new hook and setup it's various variables */
3294         hook = bridge_hook_generic(sizeof(*hook), callback, hook_pvt, destructor,
3295                 remove_flags);
3296         if (!hook) {
3297                 return -1;
3298         }
3299         hook->type = type;
3300
3301         /* Once done we put it in the container. */
3302         res = ao2_link(features->other_hooks, hook) ? 0 : -1;
3303         if (res) {
3304                 /*
3305                  * Could not link the hook into the container.
3306                  *
3307                  * Remove the hook_pvt destructor call from the hook since we
3308                  * are returning failure to install the hook.
3309                  */
3310                 hook->destructor = NULL;
3311         }
3312         ao2_ref(hook, -1);
3313
3314         return res;
3315 }
3316
3317 int ast_bridge_hangup_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_HANGUP);
3325 }
3326
3327 int ast_bridge_join_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_JOIN);
3335 }
3336
3337 int ast_bridge_leave_hook(struct ast_bridge_features *features,
3338         ast_bridge_hook_callback callback,
3339         void *hook_pvt,
3340         ast_bridge_hook_pvt_destructor destructor,
3341         enum ast_bridge_hook_remove_flags remove_flags)
3342 {
3343         return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
3344                 AST_BRIDGE_HOOK_TYPE_LEAVE);
3345 }
3346
3347 int ast_bridge_talk_detector_hook(struct ast_bridge_features *features,
3348         ast_bridge_talking_indicate_callback callback,
3349         void *hook_pvt,
3350         ast_bridge_hook_pvt_destructor destructor,
3351         enum ast_bridge_hook_remove_flags remove_flags)
3352 {
3353         ast_bridge_hook_callback hook_cb = (ast_bridge_hook_callback) callback;
3354
3355         return bridge_other_hook(features, hook_cb, hook_pvt, destructor, remove_flags,
3356                 AST_BRIDGE_HOOK_TYPE_TALK);
3357 }
3358
3359 int ast_bridge_move_hook(struct ast_bridge_features *features,
3360         ast_bridge_move_indicate_callback callback,
3361         void *hook_pvt,
3362         ast_bridge_hook_pvt_destructor destructor,
3363         enum ast_bridge_hook_remove_flags remove_flags)
3364 {
3365         ast_bridge_hook_callback hook_cb = (ast_bridge_hook_callback) callback;
3366
3367         return bridge_other_hook(features, hook_cb, hook_pvt, destructor, remove_flags,
3368                 AST_BRIDGE_HOOK_TYPE_MOVE);
3369 }
3370
3371 int ast_bridge_interval_hook(struct ast_bridge_features *features,
3372         enum ast_bridge_hook_timer_option flags,
3373         unsigned int interval,
3374         ast_bridge_hook_callback callback,
3375         void *hook_pvt,
3376         ast_bridge_hook_pvt_destructor destructor,
3377         enum ast_bridge_hook_remove_flags remove_flags)
3378 {
3379         struct ast_bridge_hook_timer *hook;
3380         int res;
3381
3382         if (!features ||!interval || !callback) {
3383                 return -1;
3384         }
3385
3386         /* Allocate new hook and setup it's various variables */
3387         hook = (struct ast_bridge_hook_timer *) bridge_hook_generic(sizeof(*hook), callback,
3388                 hook_pvt, destructor, remove_flags);
3389         if (!hook) {
3390                 return -1;
3391         }
3392         hook->generic.type = AST_BRIDGE_HOOK_TYPE_TIMER;
3393         hook->timer.interval = interval;
3394         hook->timer.trip_time = ast_tvadd(ast_tvnow(), ast_samp2tv(interval, 1000));
3395         hook->timer.seqno = ast_atomic_fetchadd_int((int *) &features->interval_sequence, +1);