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