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