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