git migration: Refactor the ASTERISK_FILE_VERSION macro
[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 static void update_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         update_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         update_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                 update_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                 update_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);
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 ast_bridge_channel *bridge_channel = data;
1583
1584         if (bridge_channel->callid) {
1585                 ast_callid_threadassoc_add(bridge_channel->callid);
1586         }
1587
1588         bridge_channel_internal_join(bridge_channel);
1589
1590         /*
1591          * cleanup
1592          *
1593          * If bridge_channel->swap is not NULL then the join failed.
1594          */
1595         ao2_t_cleanup(bridge_channel->swap, "Bridge complete: Departable impart join failed");
1596         bridge_channel->swap = NULL;
1597         ast_bridge_features_destroy(bridge_channel->features);
1598         bridge_channel->features = NULL;
1599
1600         ast_bridge_discard_after_callback(bridge_channel->chan, AST_BRIDGE_AFTER_CB_REASON_DEPART);
1601         ast_bridge_discard_after_goto(bridge_channel->chan);
1602
1603         return NULL;
1604 }
1605
1606 /*! \brief Thread responsible for independent imparted bridged channels */
1607 static void *bridge_channel_ind_thread(void *data)
1608 {
1609         struct ast_bridge_channel *bridge_channel = data;
1610         struct ast_channel *chan;
1611
1612         if (bridge_channel->callid) {
1613                 ast_callid_threadassoc_add(bridge_channel->callid);
1614         }
1615
1616         bridge_channel_internal_join(bridge_channel);
1617         chan = bridge_channel->chan;
1618
1619         /* cleanup */
1620         ast_channel_lock(chan);
1621         ast_channel_internal_bridge_channel_set(chan, NULL);
1622         ast_channel_unlock(chan);
1623         bridge_channel->chan = NULL;
1624         /* If bridge_channel->swap is not NULL then the join failed. */
1625         ao2_t_cleanup(bridge_channel->swap, "Bridge complete: Independent impart join failed");
1626         bridge_channel->swap = NULL;
1627         ast_bridge_features_destroy(bridge_channel->features);
1628         bridge_channel->features = NULL;
1629
1630         ao2_ref(bridge_channel, -1);
1631
1632         ast_bridge_run_after_callback(chan);
1633         ast_bridge_run_after_goto(chan);
1634         return NULL;
1635 }
1636
1637 int ast_bridge_impart(struct ast_bridge *bridge,
1638         struct ast_channel *chan,
1639         struct ast_channel *swap,
1640         struct ast_bridge_features *features,
1641         enum ast_bridge_impart_flags flags)
1642 {
1643         int res = 0;
1644         struct ast_bridge_channel *bridge_channel;
1645
1646         /* Imparted channels cannot have a PBX. */
1647         if (ast_channel_pbx(chan)) {
1648                 ast_log(AST_LOG_WARNING, "Channel %s has a PBX thread and cannot be imparted into bridge %s\n",
1649                         ast_channel_name(chan), bridge->uniqueid);
1650                 ast_bridge_features_destroy(features);
1651                 return -1;
1652         }
1653
1654         /* Supply an empty features structure if the caller did not. */
1655         if (!features) {
1656                 features = ast_bridge_features_new();
1657                 if (!features) {
1658                         return -1;
1659                 }
1660         }
1661
1662         /* Try to allocate a structure for the bridge channel */
1663         bridge_channel = bridge_channel_internal_alloc(bridge);
1664         if (!bridge_channel) {
1665                 ast_bridge_features_destroy(features);
1666                 return -1;
1667         }
1668
1669         ast_channel_lock(chan);
1670         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE)) {
1671                 ast_log(AST_LOG_NOTICE, "Channel %s is a zombie and cannot be imparted into bridge %s\n",
1672                         ast_channel_name(chan), bridge->uniqueid);
1673                 res = -1;
1674         } else {
1675                 ast_channel_internal_bridge_channel_set(chan, bridge_channel);
1676         }
1677         ast_channel_unlock(chan);
1678         bridge_channel->chan = chan;
1679         bridge_channel->swap = ao2_t_bump(swap, "Setting up bridge impart");
1680         bridge_channel->features = features;
1681         bridge_channel->inhibit_colp = !!(flags & AST_BRIDGE_IMPART_INHIBIT_JOIN_COLP);
1682         bridge_channel->depart_wait =
1683                 (flags & AST_BRIDGE_IMPART_CHAN_MASK) == AST_BRIDGE_IMPART_CHAN_DEPARTABLE;
1684         bridge_channel->callid = ast_read_threadstorage_callid();
1685
1686         /* allow subclass to peek at swap channel before it can hangup */
1687         if (bridge->v_table->push_peek && !res) {
1688                 struct ast_bridge_channel *bcswap = NULL;
1689
1690                 ast_bridge_lock(bridge);
1691                 if (bridge_channel->swap) {
1692                         bcswap = bridge_find_channel(bridge, bridge_channel->swap);
1693                 }
1694                 res = bridge->v_table->push_peek(bridge, bridge_channel, bcswap);
1695                 ast_bridge_unlock(bridge);
1696         }
1697
1698         /* Actually create the thread that will handle the channel */
1699         if (!res) {
1700                 if ((flags & AST_BRIDGE_IMPART_CHAN_MASK) == AST_BRIDGE_IMPART_CHAN_INDEPENDENT) {
1701                         res = ast_pthread_create_detached(&bridge_channel->thread, NULL,
1702                                 bridge_channel_ind_thread, bridge_channel);
1703                 } else {
1704                         res = ast_pthread_create(&bridge_channel->thread, NULL,
1705                                 bridge_channel_depart_thread, bridge_channel);
1706                 }
1707         }
1708
1709         if (res) {
1710                 /* cleanup */
1711                 ast_channel_lock(chan);
1712                 ast_channel_internal_bridge_channel_set(chan, NULL);
1713                 ast_channel_unlock(chan);
1714                 bridge_channel->chan = NULL;
1715                 ao2_t_cleanup(bridge_channel->swap, "Bridge complete: Impart failed");
1716                 bridge_channel->swap = NULL;
1717                 ast_bridge_features_destroy(bridge_channel->features);
1718                 bridge_channel->features = NULL;
1719
1720                 ao2_ref(bridge_channel, -1);
1721                 return -1;
1722         }
1723
1724         return 0;
1725 }
1726
1727 int ast_bridge_depart(struct ast_channel *chan)
1728 {
1729         struct ast_bridge_channel *bridge_channel;
1730         int departable;
1731
1732         ast_channel_lock(chan);
1733         bridge_channel = ast_channel_internal_bridge_channel(chan);
1734         departable = bridge_channel && bridge_channel->depart_wait;
1735         ast_channel_unlock(chan);
1736         if (!departable) {
1737                 ast_log(LOG_ERROR, "Channel %s cannot be departed.\n",
1738                         ast_channel_name(chan));
1739                 /*
1740                  * Should never happen.  It likely means that
1741                  * ast_bridge_depart() is called by two threads for the same
1742                  * channel, the channel was never imparted to be departed, or it
1743                  * has already been departed.
1744                  */
1745                 ast_assert(0);
1746                 return -1;
1747         }
1748
1749         /*
1750          * We are claiming the bridge_channel reference held by
1751          * bridge_channel_depart_thread().
1752          */
1753
1754         ast_bridge_channel_leave_bridge(bridge_channel,
1755                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
1756
1757         /* Wait for the depart thread to die */
1758         ast_debug(1, "Waiting for %p(%s) bridge thread to die.\n",
1759                 bridge_channel, ast_channel_name(bridge_channel->chan));
1760         pthread_join(bridge_channel->thread, NULL);
1761
1762         ast_channel_lock(chan);
1763         ast_channel_internal_bridge_channel_set(chan, NULL);
1764         ast_channel_unlock(chan);
1765
1766         /* We can get rid of the bridge_channel after the depart thread has died. */
1767         ao2_ref(bridge_channel, -1);
1768         return 0;
1769 }
1770
1771 int ast_bridge_remove(struct ast_bridge *bridge, struct ast_channel *chan)
1772 {
1773         struct ast_bridge_channel *bridge_channel;
1774
1775         ast_bridge_lock(bridge);
1776
1777         /* Try to find the channel that we want to remove */
1778         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
1779                 ast_bridge_unlock(bridge);
1780                 return -1;
1781         }
1782
1783         ast_bridge_channel_leave_bridge(bridge_channel,
1784                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
1785
1786         ast_bridge_unlock(bridge);
1787
1788         return 0;
1789 }
1790
1791 static void kick_it(struct ast_bridge_channel *bridge_channel, const void *payload, size_t payload_size)
1792 {
1793         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1794 }
1795
1796 int ast_bridge_kick(struct ast_bridge *bridge, struct ast_channel *chan)
1797 {
1798         struct ast_bridge_channel *bridge_channel;
1799         int res;
1800
1801         ast_bridge_lock(bridge);
1802
1803         /* Try to find the channel that we want to kick. */
1804         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
1805                 ast_bridge_unlock(bridge);
1806                 return -1;
1807         }
1808
1809         res = ast_bridge_channel_queue_callback(bridge_channel, 0, kick_it, NULL, 0);
1810
1811         ast_bridge_unlock(bridge);
1812
1813         return res;
1814 }
1815
1816 /*!
1817  * \internal
1818  * \brief Point the bridge_channel to a new bridge.
1819  * \since 12.0.0
1820  *
1821  * \param bridge_channel What is to point to a new bridge.
1822  * \param new_bridge Where the bridge channel should point.
1823  *
1824  * \return Nothing
1825  */
1826 static void bridge_channel_change_bridge(struct ast_bridge_channel *bridge_channel, struct ast_bridge *new_bridge)
1827 {
1828         struct ast_bridge *old_bridge;
1829
1830         ao2_ref(new_bridge, +1);
1831         ast_bridge_channel_lock(bridge_channel);
1832         ast_channel_lock(bridge_channel->chan);
1833         old_bridge = bridge_channel->bridge;
1834         bridge_channel->bridge = new_bridge;
1835         ast_channel_internal_bridge_set(bridge_channel->chan, new_bridge);
1836         ast_channel_unlock(bridge_channel->chan);
1837         ast_bridge_channel_unlock(bridge_channel);
1838         ao2_ref(old_bridge, -1);
1839 }
1840
1841 static void bridge_channel_moving(struct ast_bridge_channel *bridge_channel, struct ast_bridge *src, struct ast_bridge *dst)
1842 {
1843         struct ast_bridge_features *features = bridge_channel->features;
1844         struct ast_bridge_hook *hook;
1845         struct ao2_iterator iter;
1846
1847         /* Run any moving hooks. */
1848         iter = ao2_iterator_init(features->other_hooks, 0);
1849         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1850                 int remove_me;
1851                 ast_bridge_move_indicate_callback move_cb;
1852
1853                 if (hook->type != AST_BRIDGE_HOOK_TYPE_MOVE) {
1854                         continue;
1855                 }
1856                 move_cb = (ast_bridge_move_indicate_callback) hook->callback;
1857                 remove_me = move_cb(bridge_channel, hook->hook_pvt, src, dst);
1858                 if (remove_me) {
1859                         ast_debug(1, "Move detection hook %p is being removed from %p(%s)\n",
1860                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1861                         ao2_unlink(features->other_hooks, hook);
1862                 }
1863         }
1864         ao2_iterator_destroy(&iter);
1865 }
1866
1867 void bridge_do_merge(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, struct ast_bridge_channel **kick_me, unsigned int num_kick,
1868         unsigned int optimized)
1869 {
1870         struct ast_bridge_channel *bridge_channel;
1871         unsigned int idx;
1872
1873         ast_debug(1, "Merging bridge %s into bridge %s\n",
1874                 src_bridge->uniqueid, dst_bridge->uniqueid);
1875
1876         ast_bridge_publish_merge(dst_bridge, src_bridge);
1877
1878         /*
1879          * Move channels from src_bridge over to dst_bridge.
1880          *
1881          * We must use AST_LIST_TRAVERSE_SAFE_BEGIN() because
1882          * bridge_channel_internal_pull() alters the list we are traversing.
1883          */
1884         AST_LIST_TRAVERSE_SAFE_BEGIN(&src_bridge->channels, bridge_channel, entry) {
1885                 if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1886                         /*
1887                          * The channel is already leaving let it leave normally because
1888                          * pulling it may delete hooks that should run for this channel.
1889                          */
1890                         continue;
1891                 }
1892                 if (ast_test_flag(&bridge_channel->features->feature_flags,
1893                         AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
1894                         continue;
1895                 }
1896
1897                 if (kick_me) {
1898                         for (idx = 0; idx < num_kick; ++idx) {
1899                                 if (bridge_channel == kick_me[idx]) {
1900                                         ast_bridge_channel_leave_bridge(bridge_channel,
1901                                                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
1902                                         break;
1903                                 }
1904                         }
1905                 }
1906                 bridge_channel_internal_pull(bridge_channel);
1907                 if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1908                         /*
1909                          * The channel died as a result of being pulled or it was
1910                          * kicked.  Leave it pointing to the original bridge.
1911                          */
1912                         continue;
1913                 }
1914
1915                 bridge_channel_moving(bridge_channel, bridge_channel->bridge, dst_bridge);
1916
1917                 /* Point to new bridge.*/
1918                 bridge_channel_change_bridge(bridge_channel, dst_bridge);
1919
1920                 if (bridge_channel_internal_push(bridge_channel)) {
1921                         ast_bridge_features_remove(bridge_channel->features,
1922                                 AST_BRIDGE_HOOK_REMOVE_ON_PULL);
1923                         ast_bridge_channel_leave_bridge(bridge_channel,
1924                                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
1925                 }
1926         }
1927         AST_LIST_TRAVERSE_SAFE_END;
1928
1929         if (kick_me) {
1930                 /*
1931                  * Now we can kick any channels in the dst_bridge without
1932                  * potentially dissolving the bridge.
1933                  */
1934                 for (idx = 0; idx < num_kick; ++idx) {
1935                         bridge_channel = kick_me[idx];
1936                         ast_bridge_channel_lock(bridge_channel);
1937                         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
1938                                 ast_bridge_channel_leave_bridge_nolock(bridge_channel,
1939                                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
1940                                 bridge_channel_internal_pull(bridge_channel);
1941                         }
1942                         ast_bridge_channel_unlock(bridge_channel);
1943                 }
1944         }
1945
1946         bridge_reconfigured(dst_bridge, !optimized);
1947         bridge_reconfigured(src_bridge, !optimized);
1948
1949         ast_debug(1, "Merged bridge %s into bridge %s\n",
1950                 src_bridge->uniqueid, dst_bridge->uniqueid);
1951 }
1952
1953 struct merge_direction {
1954         /*! Destination merge bridge. */
1955         struct ast_bridge *dest;
1956         /*! Source merge bridge. */
1957         struct ast_bridge *src;
1958 };
1959
1960 /*!
1961  * \internal
1962  * \brief Determine which bridge should merge into the other.
1963  * \since 12.0.0
1964  *
1965  * \param bridge1 A bridge for merging
1966  * \param bridge2 A bridge for merging
1967  *
1968  * \note The two bridges are assumed already locked.
1969  *
1970  * \return Which bridge merges into which or NULL bridges if cannot merge.
1971  */
1972 static struct merge_direction bridge_merge_determine_direction(struct ast_bridge *bridge1, struct ast_bridge *bridge2)
1973 {
1974         struct merge_direction merge = { NULL, NULL };
1975         int bridge1_priority;
1976         int bridge2_priority;
1977
1978         if (!ast_test_flag(&bridge1->feature_flags,
1979                         AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)
1980                 && !ast_test_flag(&bridge2->feature_flags,
1981                         AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
1982                 /*
1983                  * Can merge either way.  Merge to the higher priority merge
1984                  * bridge.  Otherwise merge to the larger bridge.
1985                  */
1986                 bridge1_priority = bridge1->v_table->get_merge_priority(bridge1);
1987                 bridge2_priority = bridge2->v_table->get_merge_priority(bridge2);
1988                 if (bridge2_priority < bridge1_priority) {
1989                         merge.dest = bridge1;
1990                         merge.src = bridge2;
1991                 } else if (bridge1_priority < bridge2_priority) {
1992                         merge.dest = bridge2;
1993                         merge.src = bridge1;
1994                 } else {
1995                         /* Merge to the larger bridge. */
1996                         if (bridge2->num_channels <= bridge1->num_channels) {
1997                                 merge.dest = bridge1;
1998                                 merge.src = bridge2;
1999                         } else {
2000                                 merge.dest = bridge2;
2001                                 merge.src = bridge1;
2002                         }
2003                 }
2004         } else if (!ast_test_flag(&bridge1->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
2005                 && !ast_test_flag(&bridge2->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
2006                 /* Can merge only one way. */
2007                 merge.dest = bridge1;
2008                 merge.src = bridge2;
2009         } else if (!ast_test_flag(&bridge2->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
2010                 && !ast_test_flag(&bridge1->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
2011                 /* Can merge only one way. */
2012                 merge.dest = bridge2;
2013                 merge.src = bridge1;
2014         }
2015
2016         return merge;
2017 }
2018
2019 /*!
2020  * \internal
2021  * \brief Merge two bridges together
2022  * \since 12.0.0
2023  *
2024  * \param dst_bridge Destination bridge of merge.
2025  * \param src_bridge Source bridge of merge.
2026  * \param merge_best_direction TRUE if don't care about which bridge merges into the other.
2027  * \param kick_me Array of channels to kick from the bridges.
2028  * \param num_kick Number of channels in the kick_me array.
2029  *
2030  * \note The dst_bridge and src_bridge are assumed already locked.
2031  *
2032  * \retval 0 on success
2033  * \retval -1 on failure
2034  */
2035 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)
2036 {
2037         struct merge_direction merge;
2038         struct ast_bridge_channel **kick_them = NULL;
2039
2040         /* Sanity check. */
2041         ast_assert(dst_bridge && src_bridge && dst_bridge != src_bridge && (!num_kick || kick_me));
2042
2043         if (dst_bridge->dissolved || src_bridge->dissolved) {
2044                 ast_debug(1, "Can't merge bridges %s and %s, at least one bridge is dissolved.\n",
2045                         src_bridge->uniqueid, dst_bridge->uniqueid);
2046                 return -1;
2047         }
2048         if (ast_test_flag(&dst_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)
2049                 || ast_test_flag(&src_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
2050                 ast_debug(1, "Can't merge bridges %s and %s, masquerade only.\n",
2051                         src_bridge->uniqueid, dst_bridge->uniqueid);
2052                 return -1;
2053         }
2054         if (dst_bridge->inhibit_merge || src_bridge->inhibit_merge) {
2055                 ast_debug(1, "Can't merge bridges %s and %s, merging temporarily inhibited.\n",
2056                         src_bridge->uniqueid, dst_bridge->uniqueid);
2057                 return -1;
2058         }
2059
2060         if (merge_best_direction) {
2061                 merge = bridge_merge_determine_direction(dst_bridge, src_bridge);
2062         } else {
2063                 merge.dest = dst_bridge;
2064                 merge.src = src_bridge;
2065         }
2066
2067         if (!merge.dest
2068                 || ast_test_flag(&merge.dest->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
2069                 || ast_test_flag(&merge.src->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
2070                 ast_debug(1, "Can't merge bridges %s and %s, merging inhibited.\n",
2071                         src_bridge->uniqueid, dst_bridge->uniqueid);
2072                 return -1;
2073         }
2074         if (merge.src->num_channels < 2) {
2075                 /*
2076                  * For a two party bridge, a channel may be temporarily removed
2077                  * from the source bridge or the initial bridge members have not
2078                  * joined yet.
2079                  */
2080                 ast_debug(1, "Can't merge bridge %s into bridge %s, not enough channels in source bridge.\n",
2081                         merge.src->uniqueid, merge.dest->uniqueid);
2082                 return -1;
2083         }
2084         if (2 + num_kick < merge.dest->num_channels + merge.src->num_channels
2085                 && !(merge.dest->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)
2086                 && (!ast_test_flag(&merge.dest->feature_flags, AST_BRIDGE_FLAG_SMART)
2087                         || !(merge.dest->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX))) {
2088                 ast_debug(1, "Can't merge bridge %s into bridge %s, multimix is needed and it cannot be acquired.\n",
2089                         merge.src->uniqueid, merge.dest->uniqueid);
2090                 return -1;
2091         }
2092
2093         if (num_kick) {
2094                 unsigned int num_to_kick = 0;
2095                 unsigned int idx;
2096
2097                 kick_them = ast_alloca(num_kick * sizeof(*kick_them));
2098                 for (idx = 0; idx < num_kick; ++idx) {
2099                         kick_them[num_to_kick] = bridge_find_channel(merge.src, kick_me[idx]);
2100                         if (!kick_them[num_to_kick]) {
2101                                 kick_them[num_to_kick] = bridge_find_channel(merge.dest, kick_me[idx]);
2102                         }
2103                         if (kick_them[num_to_kick]) {
2104                                 ++num_to_kick;
2105                         }
2106                 }
2107
2108                 if (num_to_kick != num_kick) {
2109                         ast_debug(1, "Can't merge bridge %s into bridge %s, at least one kicked channel is not in either bridge.\n",
2110                                 merge.src->uniqueid, merge.dest->uniqueid);
2111                         return -1;
2112                 }
2113         }
2114
2115         bridge_do_merge(merge.dest, merge.src, kick_them, num_kick, 0);
2116         return 0;
2117 }
2118
2119 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)
2120 {
2121         int res;
2122
2123         /* Sanity check. */
2124         ast_assert(dst_bridge && src_bridge);
2125
2126         ast_bridge_lock_both(dst_bridge, src_bridge);
2127         res = bridge_merge_locked(dst_bridge, src_bridge, merge_best_direction, kick_me, num_kick);
2128         ast_bridge_unlock(src_bridge);
2129         ast_bridge_unlock(dst_bridge);
2130         return res;
2131 }
2132
2133 int bridge_do_move(struct ast_bridge *dst_bridge, struct ast_bridge_channel *bridge_channel, int attempt_recovery,
2134         unsigned int optimized)
2135 {
2136         struct ast_bridge *orig_bridge;
2137         int was_in_bridge;
2138         int res = 0;
2139
2140         if (bridge_channel->swap) {
2141                 ast_debug(1, "Moving %p(%s) into bridge %s swapping with %s\n",
2142                         bridge_channel, ast_channel_name(bridge_channel->chan), dst_bridge->uniqueid,
2143                         ast_channel_name(bridge_channel->swap));
2144         } else {
2145                 ast_debug(1, "Moving %p(%s) into bridge %s\n",
2146                         bridge_channel, ast_channel_name(bridge_channel->chan), dst_bridge->uniqueid);
2147         }
2148
2149         orig_bridge = bridge_channel->bridge;
2150         was_in_bridge = bridge_channel->in_bridge;
2151
2152         bridge_channel_internal_pull(bridge_channel);
2153         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2154                 /*
2155                  * The channel died as a result of being pulled.  Leave it
2156                  * pointing to the original bridge.
2157                  *
2158                  * Clear out the swap channel pointer.  A ref is not held
2159                  * by bridge_channel->swap at this point.
2160                  */
2161                 bridge_channel->swap = NULL;
2162                 bridge_reconfigured(orig_bridge, 0);
2163                 return -1;
2164         }
2165
2166         /* Point to new bridge.*/
2167         ao2_ref(orig_bridge, +1);/* Keep a ref in case the push fails. */
2168         bridge_channel_change_bridge(bridge_channel, dst_bridge);
2169
2170         bridge_channel_moving(bridge_channel, orig_bridge, dst_bridge);
2171
2172         if (bridge_channel_internal_push(bridge_channel)) {
2173                 /* Try to put the channel back into the original bridge. */
2174                 ast_bridge_features_remove(bridge_channel->features,
2175                         AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2176                 if (attempt_recovery && was_in_bridge) {
2177                         /* Point back to original bridge. */
2178                         bridge_channel_change_bridge(bridge_channel, orig_bridge);
2179
2180                         if (bridge_channel_internal_push(bridge_channel)) {
2181                                 ast_bridge_features_remove(bridge_channel->features,
2182                                         AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2183                                 ast_bridge_channel_leave_bridge(bridge_channel,
2184                                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
2185                                 bridge_channel_settle_owed_events(orig_bridge, bridge_channel);
2186                         }
2187                 } else {
2188                         ast_bridge_channel_leave_bridge(bridge_channel,
2189                                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
2190                         bridge_channel_settle_owed_events(orig_bridge, bridge_channel);
2191                 }
2192                 res = -1;
2193         } else {
2194                 bridge_channel_settle_owed_events(orig_bridge, bridge_channel);
2195         }
2196
2197         bridge_reconfigured(dst_bridge, !optimized);
2198         bridge_reconfigured(orig_bridge, !optimized);
2199         ao2_ref(orig_bridge, -1);
2200         return res;
2201 }
2202
2203 /*!
2204  * \internal
2205  * \brief Move a channel from one bridge to another.
2206  * \since 12.0.0
2207  *
2208  * \param dst_bridge Destination bridge of bridge channel move.
2209  * \param src_bridge Source bridge of bridge channel move.
2210  * \param chan Channel to move.
2211  * \param swap Channel to replace in dst_bridge.
2212  * \param attempt_recovery TRUE if failure attempts to push channel back into original bridge.
2213  *
2214  * \note The dst_bridge and src_bridge are assumed already locked.
2215  *
2216  * \retval 0 on success.
2217  * \retval -1 on failure.
2218  */
2219 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)
2220 {
2221         struct ast_bridge_channel *bridge_channel;
2222
2223         if (dst_bridge->dissolved || src_bridge->dissolved) {
2224                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, at least one bridge is dissolved.\n",
2225                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2226                 return -1;
2227         }
2228         if (ast_test_flag(&dst_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)
2229                 || ast_test_flag(&src_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
2230                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, masquerade only.\n",
2231                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2232                 return -1;
2233         }
2234         if (dst_bridge->inhibit_merge || src_bridge->inhibit_merge) {
2235                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, temporarily inhibited.\n",
2236                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2237                 return -1;
2238         }
2239
2240         bridge_channel = bridge_find_channel(src_bridge, chan);
2241         if (!bridge_channel) {
2242                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel not in bridge.\n",
2243                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2244                 return -1;
2245         }
2246         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2247                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel leaving bridge.\n",
2248                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2249                 return -1;
2250         }
2251         if (ast_test_flag(&bridge_channel->features->feature_flags,
2252                 AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
2253                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel immovable.\n",
2254                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2255                 return -1;
2256         }
2257
2258         if (swap) {
2259                 struct ast_bridge_channel *bridge_channel_swap;
2260
2261                 bridge_channel_swap = bridge_find_channel(dst_bridge, swap);
2262                 if (!bridge_channel_swap) {
2263                         ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, swap channel %s not in bridge.\n",
2264                                 ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid,
2265                                 ast_channel_name(swap));
2266                         return -1;
2267                 }
2268                 if (bridge_channel_swap->state != BRIDGE_CHANNEL_STATE_WAIT) {
2269                         ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, swap channel %s leaving bridge.\n",
2270                                 ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid,
2271                                 ast_channel_name(swap));
2272                         return -1;
2273                 }
2274         }
2275
2276         bridge_channel->swap = swap;
2277         return bridge_do_move(dst_bridge, bridge_channel, attempt_recovery, 0);
2278 }
2279
2280 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)
2281 {
2282         int res;
2283
2284         ast_bridge_lock_both(dst_bridge, src_bridge);
2285         res = bridge_move_locked(dst_bridge, src_bridge, chan, swap, attempt_recovery);
2286         ast_bridge_unlock(src_bridge);
2287         ast_bridge_unlock(dst_bridge);
2288         return res;
2289 }
2290
2291 int ast_bridge_add_channel(struct ast_bridge *bridge, struct ast_channel *chan,
2292         struct ast_bridge_features *features, int play_tone, const char *xfersound)
2293 {
2294         RAII_VAR(struct ast_bridge *, chan_bridge, NULL, ao2_cleanup);
2295         RAII_VAR(struct ast_channel *, yanked_chan, NULL, ao2_cleanup);
2296
2297         ast_channel_lock(chan);
2298         chan_bridge = ast_channel_get_bridge(chan);
2299         ast_channel_unlock(chan);
2300
2301         if (chan_bridge) {
2302                 struct ast_bridge_channel *bridge_channel;
2303
2304                 ast_bridge_lock_both(bridge, chan_bridge);
2305                 bridge_channel = bridge_find_channel(chan_bridge, chan);
2306
2307                 if (bridge_move_locked(bridge, chan_bridge, chan, NULL, 1)) {
2308                         ast_bridge_unlock(chan_bridge);
2309                         ast_bridge_unlock(bridge);
2310                         return -1;
2311                 }
2312
2313                 /*
2314                  * bridge_move_locked() will implicitly ensure that
2315                  * bridge_channel is not NULL.
2316                  */
2317                 ast_assert(bridge_channel != NULL);
2318
2319                 /*
2320                  * Additional checks if the channel we just stole dissolves the
2321                  * original bridge.
2322                  */
2323                 bridge_dissolve_check_stolen(chan_bridge, bridge_channel);
2324                 ast_bridge_unlock(chan_bridge);
2325                 ast_bridge_unlock(bridge);
2326
2327                 /* The channel was in a bridge so it is not getting any new features. */
2328                 ast_bridge_features_destroy(features);
2329         } else {
2330                 /* Slightly less easy case. We need to yank channel A from
2331                  * where he currently is and impart him into our bridge.
2332                  */
2333                 yanked_chan = ast_channel_yank(chan);
2334                 if (!yanked_chan) {
2335                         ast_log(LOG_WARNING, "Could not gain control of channel %s\n", ast_channel_name(chan));
2336                         return -1;
2337                 }
2338                 if (ast_channel_state(yanked_chan) != AST_STATE_UP) {
2339                         ast_answer(yanked_chan);
2340                 }
2341                 ast_channel_ref(yanked_chan);
2342                 if (ast_bridge_impart(bridge, yanked_chan, NULL, features,
2343                         AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
2344                         /* It is possible for us to yank a channel and have some other
2345                          * thread start a PBX on the channl after we yanked it. In particular,
2346                          * this can theoretically happen on the ;2 of a Local channel if we
2347                          * yank it prior to the ;1 being answered. Make sure that it isn't
2348                          * executing a PBX before hanging it up.
2349                          */
2350                         if (ast_channel_pbx(yanked_chan)) {
2351                                 ast_channel_unref(yanked_chan);
2352                         } else {
2353                                 ast_hangup(yanked_chan);
2354                         }
2355                         return -1;
2356                 }
2357         }
2358
2359         if (play_tone && !ast_strlen_zero(xfersound)) {
2360                 struct ast_channel *play_chan = yanked_chan ?: chan;
2361                 RAII_VAR(struct ast_bridge_channel *, play_bridge_channel, NULL, ao2_cleanup);
2362
2363                 ast_channel_lock(play_chan);
2364                 play_bridge_channel = ast_channel_get_bridge_channel(play_chan);
2365                 ast_channel_unlock(play_chan);
2366
2367                 if (!play_bridge_channel) {
2368                         ast_log(LOG_WARNING, "Unable to play tone for channel %s. No longer in a bridge.\n",
2369                                 ast_channel_name(play_chan));
2370                 } else {
2371                         ast_bridge_channel_queue_playfile(play_bridge_channel, NULL, xfersound, NULL);
2372                 }
2373         }
2374         return 0;
2375 }
2376
2377 static int bridge_allows_optimization(struct ast_bridge *bridge)
2378 {
2379         return !(bridge->inhibit_merge
2380                 || bridge->dissolved
2381                 || ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY));
2382 }
2383
2384 /*!
2385  * \internal
2386  * \brief Lock the unreal channel stack for chan and prequalify it.
2387  * \since 12.0.0
2388  *
2389  * \param chan Unreal channel writing a frame into the channel driver.
2390  *
2391  * \note It is assumed that chan is already locked.
2392  *
2393  * \retval bridge on success with bridge and bridge_channel locked.
2394  * \retval NULL if cannot do optimization now.
2395  */
2396 static struct ast_bridge *optimize_lock_chan_stack(struct ast_channel *chan)
2397 {
2398         struct ast_bridge *bridge;
2399         struct ast_bridge_channel *bridge_channel;
2400
2401         if (!AST_LIST_EMPTY(ast_channel_readq(chan))) {
2402                 return NULL;
2403         }
2404         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF)) {
2405                 return NULL;
2406         }
2407         if (ast_channel_has_audio_frame_or_monitor(chan)) {
2408                 /* Channel has an active monitor, audiohook, or framehook. */
2409                 return NULL;
2410         }
2411         bridge_channel = ast_channel_internal_bridge_channel(chan);
2412         if (!bridge_channel || ast_bridge_channel_trylock(bridge_channel)) {
2413                 return NULL;
2414         }
2415         bridge = bridge_channel->bridge;
2416         if (bridge_channel->activity != BRIDGE_CHANNEL_THREAD_SIMPLE
2417                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2418                 || ast_bridge_trylock(bridge)) {
2419                 ast_bridge_channel_unlock(bridge_channel);
2420                 return NULL;
2421         }
2422         if (!bridge_channel_internal_allows_optimization(bridge_channel) ||
2423                         !bridge_allows_optimization(bridge)) {
2424                 ast_bridge_unlock(bridge);
2425                 ast_bridge_channel_unlock(bridge_channel);
2426                 return NULL;
2427         }
2428         return bridge;
2429 }
2430
2431 /*!
2432  * \internal
2433  * \brief Lock the unreal channel stack for peer and prequalify it.
2434  * \since 12.0.0
2435  *
2436  * \param peer Other unreal channel in the pair.
2437  *
2438  * \retval bridge on success with bridge, bridge_channel, and peer locked.
2439  * \retval NULL if cannot do optimization now.
2440  */
2441 static struct ast_bridge *optimize_lock_peer_stack(struct ast_channel *peer)
2442 {
2443         struct ast_bridge *bridge;
2444         struct ast_bridge_channel *bridge_channel;
2445
2446         if (ast_channel_trylock(peer)) {
2447                 return NULL;
2448         }
2449         if (!AST_LIST_EMPTY(ast_channel_readq(peer))) {
2450                 ast_channel_unlock(peer);
2451                 return NULL;
2452         }
2453         if (ast_test_flag(ast_channel_flags(peer), AST_FLAG_EMULATE_DTMF)) {
2454                 ast_channel_unlock(peer);
2455                 return NULL;
2456         }
2457         if (ast_channel_has_audio_frame_or_monitor(peer)) {
2458                 /* Peer has an active monitor, audiohook, or framehook. */
2459                 ast_channel_unlock(peer);
2460                 return NULL;
2461         }
2462         bridge_channel = ast_channel_internal_bridge_channel(peer);
2463         if (!bridge_channel || ast_bridge_channel_trylock(bridge_channel)) {
2464                 ast_channel_unlock(peer);
2465                 return NULL;
2466         }
2467         bridge = bridge_channel->bridge;
2468         if (bridge_channel->activity != BRIDGE_CHANNEL_THREAD_IDLE
2469                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2470                 || ast_bridge_trylock(bridge)) {
2471                 ast_bridge_channel_unlock(bridge_channel);
2472                 ast_channel_unlock(peer);
2473                 return NULL;
2474         }
2475         if (!bridge_allows_optimization(bridge) ||
2476                         !bridge_channel_internal_allows_optimization(bridge_channel)) {
2477                 ast_bridge_unlock(bridge);
2478                 ast_bridge_channel_unlock(bridge_channel);
2479                 ast_channel_unlock(peer);
2480                 return NULL;
2481         }
2482         return bridge;
2483 }
2484
2485 /*!
2486  * \internal
2487  * \brief Indicates allowability of a swap optimization
2488  */
2489 enum bridge_allow_swap {
2490         /*! Bridges cannot allow for a swap optimization to occur */
2491         SWAP_PROHIBITED,
2492         /*! Bridge swap optimization can occur into the chan_bridge */
2493         SWAP_TO_CHAN_BRIDGE,
2494         /*! Bridge swap optimization can occur into the peer_bridge */
2495         SWAP_TO_PEER_BRIDGE,
2496 };
2497
2498 /*!
2499  * \internal
2500  * \brief Determine if two bridges allow for swap optimization to occur
2501  *
2502  * \param chan_bridge First bridge being tested
2503  * \param peer_bridge Second bridge being tested
2504  * \return Allowability of swap optimization
2505  */
2506 static enum bridge_allow_swap bridges_allow_swap_optimization(struct ast_bridge *chan_bridge,
2507                 struct ast_bridge *peer_bridge)
2508 {
2509         int chan_priority;
2510         int peer_priority;
2511
2512         if (!ast_test_flag(&chan_bridge->feature_flags,
2513                         AST_BRIDGE_FLAG_SWAP_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM |
2514                         AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2515                 && !ast_test_flag(&peer_bridge->feature_flags,
2516                         AST_BRIDGE_FLAG_SWAP_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM |
2517                         AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)) {
2518                 /*
2519                  * Can swap either way.  Swap to the higher priority merge
2520                  * bridge.
2521                  */
2522                 chan_priority = chan_bridge->v_table->get_merge_priority(chan_bridge);
2523                 peer_priority = peer_bridge->v_table->get_merge_priority(peer_bridge);
2524                 if (chan_bridge->num_channels == 2
2525                         && chan_priority <= peer_priority) {
2526                         return SWAP_TO_PEER_BRIDGE;
2527                 } else if (peer_bridge->num_channels == 2
2528                         && peer_priority <= chan_priority) {
2529                         return SWAP_TO_CHAN_BRIDGE;
2530                 }
2531         } else if (chan_bridge->num_channels == 2
2532                 && !ast_test_flag(&chan_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM | AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2533                 && !ast_test_flag(&peer_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_TO)) {
2534                 /* Can swap optimize only one way. */
2535                 return SWAP_TO_PEER_BRIDGE;
2536         } else if (peer_bridge->num_channels == 2
2537                 && !ast_test_flag(&peer_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM | AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2538                 && !ast_test_flag(&chan_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_TO)) {
2539                 /* Can swap optimize only one way. */
2540                 return SWAP_TO_CHAN_BRIDGE;
2541         }
2542
2543         return SWAP_PROHIBITED;
2544 }
2545
2546 /*!
2547  * \internal
2548  * \brief Check and attempt to swap optimize out the unreal channels.
2549  * \since 12.0.0
2550  *
2551  * \param chan_bridge
2552  * \param chan_bridge_channel
2553  * \param peer_bridge
2554  * \param peer_bridge_channel
2555  * \param pvt Unreal data containing callbacks to call if the optimization actually
2556  * happens
2557  *
2558  * \retval 1 if unreal channels failed to optimize out.
2559  * \retval 0 if unreal channels were not optimized out.
2560  * \retval -1 if unreal channels were optimized out.
2561  */
2562 static int try_swap_optimize_out(struct ast_bridge *chan_bridge,
2563         struct ast_bridge_channel *chan_bridge_channel, struct ast_bridge *peer_bridge,
2564         struct ast_bridge_channel *peer_bridge_channel,
2565         struct ast_unreal_pvt *pvt)
2566 {
2567         struct ast_bridge *dst_bridge;
2568         struct ast_bridge_channel *dst_bridge_channel;
2569         struct ast_bridge_channel *src_bridge_channel;
2570         struct ast_bridge_channel *other;
2571         int res = 1;
2572
2573         switch (bridges_allow_swap_optimization(chan_bridge, peer_bridge)) {
2574         case SWAP_TO_CHAN_BRIDGE:
2575                 dst_bridge = chan_bridge;
2576                 dst_bridge_channel = chan_bridge_channel;
2577                 src_bridge_channel = peer_bridge_channel;
2578                 break;
2579         case SWAP_TO_PEER_BRIDGE:
2580                 dst_bridge = peer_bridge;
2581                 dst_bridge_channel = peer_bridge_channel;
2582                 src_bridge_channel = chan_bridge_channel;
2583                 break;
2584         case SWAP_PROHIBITED:
2585         default:
2586                 return 0;
2587         }
2588
2589         other = ast_bridge_channel_peer(src_bridge_channel);
2590         if (other && other->state == BRIDGE_CHANNEL_STATE_WAIT) {
2591                 unsigned int id;
2592
2593                 if (ast_channel_trylock(other->chan)) {
2594                         return 1;
2595                 }
2596
2597                 id = ast_atomic_fetchadd_int((int *) &optimization_id, +1);
2598
2599                 ast_verb(4, "Move-swap optimizing %s <-- %s.\n",
2600                         ast_channel_name(dst_bridge_channel->chan),
2601                         ast_channel_name(other->chan));
2602
2603                 if (pvt && !ast_test_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN) && pvt->callbacks
2604                                 && pvt->callbacks->optimization_started) {
2605                         pvt->callbacks->optimization_started(pvt, other->chan,
2606                                         dst_bridge_channel->chan == pvt->owner ? AST_UNREAL_OWNER : AST_UNREAL_CHAN,
2607                                         id);
2608                         ast_set_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN);
2609                 }
2610                 other->swap = dst_bridge_channel->chan;
2611                 if (!bridge_do_move(dst_bridge, other, 1, 1)) {
2612                         ast_bridge_channel_leave_bridge(src_bridge_channel,
2613                                 BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
2614                         res = -1;
2615                 }
2616                 if (pvt && pvt->callbacks && pvt->callbacks->optimization_finished) {
2617                         pvt->callbacks->optimization_finished(pvt, res == 1, id);
2618                 }
2619                 ast_channel_unlock(other->chan);
2620         }
2621         return res;
2622 }
2623
2624 /*!
2625  * \internal
2626  * \brief Indicates allowability of a merge optimization
2627  */
2628 enum bridge_allow_merge {
2629         /*! Bridge properties prohibit merge optimization */
2630         MERGE_PROHIBITED,
2631         /*! Merge optimization cannot occur because the source bridge has too few channels */
2632         MERGE_NOT_ENOUGH_CHANNELS,
2633         /*! Merge optimization cannot occur because multimix capability could not be requested */
2634         MERGE_NO_MULTIMIX,
2635         /*! Merge optimization allowed between bridges */
2636         MERGE_ALLOWED,
2637 };
2638
2639 /*!
2640  * \internal
2641  * \brief Determines allowability of a merge optimization
2642  *
2643  * \note The merge output parameter is undefined if MERGE_PROHIBITED is returned. For success
2644  * and other failure returns, a merge direction was determined, and the parameter is safe to
2645  * access.
2646  *
2647  * \param chan_bridge First bridge being tested
2648  * \param peer_bridge Second bridge being tested
2649  * \param num_kick_channels The number of channels to remove from the bridges during merging
2650  * \param[out] merge Indicates the recommended direction for the bridge merge
2651  */
2652 static enum bridge_allow_merge bridges_allow_merge_optimization(struct ast_bridge *chan_bridge,
2653                 struct ast_bridge *peer_bridge, int num_kick_channels, struct merge_direction *merge)
2654 {
2655         *merge = bridge_merge_determine_direction(chan_bridge, peer_bridge);
2656         if (!merge->dest) {
2657                 return MERGE_PROHIBITED;
2658         }
2659         if (merge->src->num_channels < 2) {
2660                 return MERGE_NOT_ENOUGH_CHANNELS;
2661         } else if ((2 + num_kick_channels) < merge->dest->num_channels + merge->src->num_channels
2662                 && !(merge->dest->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)
2663                 && (!ast_test_flag(&merge->dest->feature_flags, AST_BRIDGE_FLAG_SMART)
2664                         || !(merge->dest->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX))) {
2665                 return MERGE_NO_MULTIMIX;
2666         }
2667
2668         return MERGE_ALLOWED;
2669 }
2670
2671 /*!
2672  * \internal
2673  * \brief Check and attempt to merge optimize out the unreal channels.
2674  * \since 12.0.0
2675  *
2676  * \param chan_bridge
2677  * \param chan_bridge_channel
2678  * \param peer_bridge
2679  * \param peer_bridge_channel
2680  * \param pvt Unreal data containing callbacks to call if the optimization actually
2681  * happens
2682  *
2683  * \retval 0 if unreal channels were not optimized out.
2684  * \retval -1 if unreal channels were optimized out.
2685  */
2686 static int try_merge_optimize_out(struct ast_bridge *chan_bridge,
2687         struct ast_bridge_channel *chan_bridge_channel, struct ast_bridge *peer_bridge,
2688         struct ast_bridge_channel *peer_bridge_channel,
2689         struct ast_unreal_pvt *pvt)
2690 {
2691         struct merge_direction merge;
2692         struct ast_bridge_channel *kick_me[] = {
2693                 chan_bridge_channel,
2694                 peer_bridge_channel,
2695         };
2696         unsigned int id;
2697
2698         switch (bridges_allow_merge_optimization(chan_bridge, peer_bridge, ARRAY_LEN(kick_me), &merge)) {
2699         case MERGE_ALLOWED:
2700                 break;
2701         case MERGE_PROHIBITED:
2702                 return 0;
2703         case MERGE_NOT_ENOUGH_CHANNELS:
2704                 ast_debug(4, "Can't optimize %s -- %s out, not enough channels in bridge %s.\n",
2705                         ast_channel_name(chan_bridge_channel->chan),
2706                         ast_channel_name(peer_bridge_channel->chan),
2707                         merge.src->uniqueid);
2708                 return 0;
2709         case MERGE_NO_MULTIMIX:
2710                 ast_debug(4, "Can't optimize %s -- %s out, multimix is needed and it cannot be acquired.\n",
2711                         ast_channel_name(chan_bridge_channel->chan),
2712                         ast_channel_name(peer_bridge_channel->chan));
2713                 return 0;
2714         }
2715
2716         ast_verb(4, "Merge optimizing %s -- %s out.\n",
2717                 ast_channel_name(chan_bridge_channel->chan),
2718                 ast_channel_name(peer_bridge_channel->chan));
2719
2720         id = ast_atomic_fetchadd_int((int *) &optimization_id, +1);
2721
2722         if (pvt && !ast_test_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN) && pvt->callbacks
2723                         && pvt->callbacks->optimization_started) {
2724                 pvt->callbacks->optimization_started(pvt, NULL,
2725                                 merge.dest == ast_channel_internal_bridge(pvt->owner) ? AST_UNREAL_OWNER : AST_UNREAL_CHAN,
2726                                 id);
2727                 ast_set_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN);
2728         }
2729         bridge_do_merge(merge.dest, merge.src, kick_me, ARRAY_LEN(kick_me), 1);
2730         if (pvt && pvt->callbacks && pvt->callbacks->optimization_finished) {
2731                 pvt->callbacks->optimization_finished(pvt, 1, id);
2732         }
2733
2734         return -1;
2735 }
2736
2737 int ast_bridge_unreal_optimize_out(struct ast_channel *chan, struct ast_channel *peer, struct ast_unreal_pvt *pvt)
2738 {
2739         struct ast_bridge *chan_bridge;
2740         struct ast_bridge *peer_bridge;
2741         struct ast_bridge_channel *chan_bridge_channel;
2742         struct ast_bridge_channel *peer_bridge_channel;
2743         int res = 0;
2744
2745         chan_bridge = optimize_lock_chan_stack(chan);
2746         if (!chan_bridge) {
2747                 return res;
2748         }
2749         chan_bridge_channel = ast_channel_internal_bridge_channel(chan);
2750
2751         peer_bridge = optimize_lock_peer_stack(peer);
2752         if (peer_bridge) {
2753                 peer_bridge_channel = ast_channel_internal_bridge_channel(peer);
2754
2755                 res = try_swap_optimize_out(chan_bridge, chan_bridge_channel,
2756                         peer_bridge, peer_bridge_channel, pvt);
2757                 if (!res) {
2758                         res = try_merge_optimize_out(chan_bridge, chan_bridge_channel,
2759                                 peer_bridge, peer_bridge_channel, pvt);
2760                 } else if (0 < res) {
2761                         res = 0;
2762                 }
2763
2764                 /* Release peer locks. */
2765                 ast_bridge_unlock(peer_bridge);
2766                 ast_bridge_channel_unlock(peer_bridge_channel);
2767                 ast_channel_unlock(peer);
2768         }
2769
2770         /* Release chan locks. */
2771         ast_bridge_unlock(chan_bridge);
2772         ast_bridge_channel_unlock(chan_bridge_channel);
2773
2774         return res;
2775 }
2776
2777 enum ast_bridge_optimization ast_bridges_allow_optimization(struct ast_bridge *chan_bridge,
2778                 struct ast_bridge *peer_bridge)
2779 {
2780         struct merge_direction merge;
2781
2782         if (!bridge_allows_optimization(chan_bridge) || !bridge_allows_optimization(peer_bridge)) {
2783                 return AST_BRIDGE_OPTIMIZE_PROHIBITED;
2784         }
2785
2786         switch (bridges_allow_swap_optimization(chan_bridge, peer_bridge)) {
2787         case SWAP_TO_CHAN_BRIDGE:
2788                 return AST_BRIDGE_OPTIMIZE_SWAP_TO_CHAN_BRIDGE;
2789         case SWAP_TO_PEER_BRIDGE:
2790                 return AST_BRIDGE_OPTIMIZE_SWAP_TO_PEER_BRIDGE;
2791         case SWAP_PROHIBITED:
2792         default:
2793                 break;
2794         }
2795
2796         /* Two channels will be kicked from the bridges, the unreal;1 and unreal;2 channels */
2797         if (bridges_allow_merge_optimization(chan_bridge, peer_bridge, 2, &merge) != MERGE_ALLOWED) {
2798                 return AST_BRIDGE_OPTIMIZE_PROHIBITED;
2799         }
2800
2801         if (merge.dest == chan_bridge) {
2802                 return AST_BRIDGE_OPTIMIZE_MERGE_TO_CHAN_BRIDGE;
2803         } else {
2804                 return AST_BRIDGE_OPTIMIZE_MERGE_TO_PEER_BRIDGE;
2805         }
2806 }
2807
2808 /*!
2809  * \internal
2810  * \brief Adjust the bridge merge inhibit request count.
2811  * \since 12.0.0
2812  *
2813  * \param bridge What to operate on.
2814  * \param request Inhibit request increment.
2815  *     (Positive to add requests.  Negative to remove requests.)
2816  *
2817  * \note This function assumes bridge is locked.
2818  *
2819  * \return Nothing
2820  */
2821 void bridge_merge_inhibit_nolock(struct ast_bridge *bridge, int request)
2822 {
2823         int new_request;
2824
2825         new_request = bridge->inhibit_merge + request;
2826         ast_assert(0 <= new_request);
2827         bridge->inhibit_merge = new_request;
2828 }
2829
2830 void ast_bridge_merge_inhibit(struct ast_bridge *bridge, int request)
2831 {
2832         ast_bridge_lock(bridge);
2833         bridge_merge_inhibit_nolock(bridge, request);
2834         ast_bridge_unlock(bridge);
2835 }
2836
2837 int ast_bridge_suspend(struct ast_bridge *bridge, struct ast_channel *chan)
2838 {
2839         struct ast_bridge_channel *bridge_channel;
2840 /* XXX ASTERISK-21271 the case of a disolved bridge while channel is suspended is not handled. */
2841 /* XXX ASTERISK-21271 suspend/unsuspend needs to be rethought. The caller must block until it has successfully suspended the channel for temporary control. */
2842 /* 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. */
2843
2844         ast_bridge_lock(bridge);
2845
2846         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
2847                 ast_bridge_unlock(bridge);
2848                 return -1;
2849         }
2850
2851         bridge_channel_internal_suspend_nolock(bridge_channel);
2852
2853         ast_bridge_unlock(bridge);
2854
2855         return 0;
2856 }
2857
2858 int ast_bridge_unsuspend(struct ast_bridge *bridge, struct ast_channel *chan)
2859 {
2860         struct ast_bridge_channel *bridge_channel;
2861 /* XXX ASTERISK-21271 the case of a disolved bridge while channel is suspended is not handled. */
2862
2863         ast_bridge_lock(bridge);
2864
2865         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
2866                 ast_bridge_unlock(bridge);
2867                 return -1;
2868         }
2869
2870         bridge_channel_internal_unsuspend_nolock(bridge_channel);
2871
2872         ast_bridge_unlock(bridge);
2873
2874         return 0;
2875 }
2876
2877 void ast_bridge_technology_suspend(struct ast_bridge_technology *technology)
2878 {
2879         technology->suspended = 1;
2880 }
2881
2882 void ast_bridge_technology_unsuspend(struct ast_bridge_technology *technology)
2883 {
2884         /*
2885          * XXX We may want the act of unsuspending a bridge technology
2886          * to prod all existing bridges to see if they should start
2887          * using it.
2888          */
2889         technology->suspended = 0;
2890 }
2891
2892 int ast_bridge_features_register(enum ast_bridge_builtin_feature feature, ast_bridge_hook_callback callback, const char *dtmf)
2893 {
2894         if (ARRAY_LEN(builtin_features_handlers) <= feature
2895                 || builtin_features_handlers[feature]) {
2896                 return -1;
2897         }
2898
2899         if (!ast_strlen_zero(dtmf)) {
2900                 ast_copy_string(builtin_features_dtmf[feature], dtmf, sizeof(builtin_features_dtmf[feature]));
2901         }
2902
2903         builtin_features_handlers[feature] = callback;
2904
2905         return 0;
2906 }
2907
2908 int ast_bridge_features_unregister(enum ast_bridge_builtin_feature feature)
2909 {
2910         if (ARRAY_LEN(builtin_features_handlers) <= feature
2911                 || !builtin_features_handlers[feature]) {
2912                 return -1;
2913         }
2914
2915         builtin_features_handlers[feature] = NULL;
2916
2917         return 0;
2918 }
2919
2920 int ast_bridge_features_do(enum ast_bridge_builtin_feature feature, struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2921 {
2922         ast_bridge_hook_callback callback;
2923
2924         if (ARRAY_LEN(builtin_features_handlers) <= feature) {
2925                 return -1;
2926         }
2927
2928         callback = builtin_features_handlers[feature];
2929         if (!callback) {
2930                 return -1;
2931         }
2932         callback(bridge_channel, hook_pvt);
2933
2934         return 0;
2935 }
2936
2937 int ast_bridge_interval_register(enum ast_bridge_builtin_interval interval, ast_bridge_builtin_set_limits_fn callback)
2938 {
2939         if (ARRAY_LEN(builtin_interval_handlers) <= interval
2940                 || builtin_interval_handlers[interval]) {
2941                 return -1;
2942         }
2943
2944         builtin_interval_handlers[interval] = callback;
2945
2946         return 0;
2947 }
2948
2949 int ast_bridge_interval_unregister(enum ast_bridge_builtin_interval interval)
2950 {
2951         if (ARRAY_LEN(builtin_interval_handlers) <= interval
2952                 || !builtin_interval_handlers[interval]) {
2953                 return -1;
2954         }
2955
2956         builtin_interval_handlers[interval] = NULL;
2957
2958         return 0;
2959
2960 }
2961
2962 /*!
2963  * \internal
2964  * \brief Bridge hook destructor.
2965  * \since 12.0.0
2966  *
2967  * \param vhook Object to destroy.
2968  *
2969  * \return Nothing
2970  */
2971 static void bridge_hook_destroy(void *vhook)
2972 {
2973         struct ast_bridge_hook *hook = vhook;
2974
2975         if (hook->destructor) {
2976                 hook->destructor(hook->hook_pvt);
2977         }
2978 }
2979
2980 /*!
2981  * \internal
2982  * \brief Allocate and setup a generic bridge hook.
2983  * \since 12.0.0
2984  *
2985  * \param size How big an object to allocate.
2986  * \param callback Function to execute upon activation
2987  * \param hook_pvt Unique data
2988  * \param destructor Optional destructor callback for hook_pvt data
2989  * \param remove_flags Dictates what situations the hook should be removed.
2990  *
2991  * \retval hook on success.
2992  * \retval NULL on error.
2993  */
2994 static struct ast_bridge_hook *bridge_hook_generic(size_t size,
2995         ast_bridge_hook_callback callback,
2996         void *hook_pvt,
2997         ast_bridge_hook_pvt_destructor destructor,
2998         enum ast_bridge_hook_remove_flags remove_flags)
2999 {
3000         struct ast_bridge_hook *hook;
3001
3002         /* Allocate new hook and setup it's basic variables */
3003         hook = ao2_alloc_options(size, bridge_hook_destroy, AO2_ALLOC_OPT_LOCK_NOLOCK);
3004         if (hook) {
3005                 hook->callback = callback;
3006                 hook->destructor = destructor;
3007                 hook->hook_pvt = hook_pvt;
3008                 ast_set_flag(&hook->remove_flags, remove_flags);
3009         }
3010
3011         return hook;
3012 }
3013
3014 int ast_bridge_dtmf_hook(struct ast_bridge_features *features,
3015         const char *dtmf,
3016         ast_bridge_hook_callback callback,
3017         void *hook_pvt,
3018         ast_bridge_hook_pvt_destructor destructor,
3019         enum ast_bridge_hook_remove_flags remove_flags)
3020 {
3021         struct ast_bridge_hook_dtmf *hook;
3022         int res;
3023
3024         /* Allocate new hook and setup it's various variables */
3025         hook = (struct ast_bridge_hook_dtmf *) bridge_hook_generic(sizeof(*hook), callback,
3026                 hook_pvt, destructor, remove_flags);
3027         if (!hook) {
3028                 return -1;
3029         }
3030         hook->generic.type = AST_BRIDGE_HOOK_TYPE_DTMF;
3031         ast_copy_string(hook->dtmf.code, dtmf, sizeof(hook->dtmf.code));
3032
3033         /* Once done we put it in the container. */
3034         res = ao2_link(features->dtmf_hooks, hook) ? 0 : -1;
3035         if (res) {
3036                 /*
3037                  * Could not link the hook into the container.
3038                  *
3039                  * Remove the hook_pvt destructor call from the hook since we
3040                  * are returning failure to install the hook.
3041                  */
3042                 hook->generic.destructor = NULL;
3043         }
3044         ao2_ref(hook, -1);
3045
3046         return res;
3047 }
3048
3049 /*!
3050  * \internal
3051  * \brief Attach an other hook to a bridge features structure
3052  *
3053  * \param features Bridge features structure
3054  * \param callback Function to execute upon activation
3055  * \param hook_pvt Unique data
3056  * \param destructor Optional destructor callback for hook_pvt data
3057  * \param remove_flags Dictates what situations the hook should be removed.
3058  * \param type What type of hook is being attached.
3059  *
3060  * \retval 0 on success
3061  * \retval -1 on failure (The caller must cleanup any hook_pvt resources.)
3062  */
3063 static int bridge_other_hook(struct ast_bridge_features *features,
3064         ast_bridge_hook_callback callback,
3065         void *hook_pvt,
3066         ast_bridge_hook_pvt_destructor destructor,
3067         enum ast_bridge_hook_remove_flags remove_flags,
3068         enum ast_bridge_hook_type type)
3069 {
3070         struct ast_bridge_hook *hook;
3071         int res;
3072
3073         /* Allocate new hook and setup it's various variables */
3074         hook = bridge_hook_generic(sizeof(*hook), callback, hook_pvt, destructor,
3075                 remove_flags);
3076         if (!hook) {
3077                 return -1;
3078         }
3079         hook->type = type;
3080
3081         /* Once done we put it in the container. */
3082         res = ao2_link(features->other_hooks, hook) ? 0 : -1;
3083         if (res) {
3084                 /*
3085                  * Could not link the hook into the container.
3086                  *
3087                  * Remove the hook_pvt destructor call from the hook since we
3088                  * are returning failure to install the hook.
3089                  */
3090                 hook->destructor = NULL;
3091         }
3092         ao2_ref(hook, -1);
3093
3094         return res;
3095 }
3096
3097 int ast_bridge_hangup_hook(struct ast_bridge_features *features,
3098         ast_bridge_hook_callback callback,
3099         void *hook_pvt,
3100         ast_bridge_hook_pvt_destructor destructor,
3101         enum ast_bridge_hook_remove_flags remove_flags)
3102 {
3103         return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
3104                 AST_BRIDGE_HOOK_TYPE_HANGUP);
3105 }
3106
3107 int ast_bridge_join_hook(struct ast_bridge_features *features,
3108         ast_bridge_hook_callback callback,
3109         void *hook_pvt,
3110         ast_bridge_hook_pvt_destructor destructor,
3111         enum ast_bridge_hook_remove_flags remove_flags)
3112 {
3113         return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
3114                 AST_BRIDGE_HOOK_TYPE_JOIN);
3115 }
3116
3117 int ast_bridge_leave_hook(struct ast_bridge_features *features,
3118         ast_bridge_hook_callback callback,
3119         void *hook_pvt,
3120         ast_bridge_hook_pvt_destructor destructor,
3121         enum ast_bridge_hook_remove_flags remove_flags)
3122 {
3123         return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
3124                 AST_BRIDGE_HOOK_TYPE_LEAVE);
3125 }
3126
3127 int ast_bridge_talk_detector_hook(struct ast_bridge_features *features,
3128         ast_bridge_talking_indicate_callback callback,
3129         void *hook_pvt,
3130         ast_bridge_hook_pvt_destructor destructor,
3131         enum ast_bridge_hook_remove_flags remove_flags)
3132 {
3133         ast_bridge_hook_callback hook_cb = (ast_bridge_hook_callback) callback;
3134
3135         return bridge_other_hook(features, hook_cb, hook_pvt, destructor, remove_flags,
3136                 AST_BRIDGE_HOOK_TYPE_TALK);
3137 }
3138
3139 int ast_bridge_move_hook(struct ast_bridge_features *features,
3140         ast_bridge_move_indicate_callback callback,
3141         void *hook_pvt,
3142         ast_bridge_hook_pvt_destructor destructor,
3143         enum ast_bridge_hook_remove_flags remove_flags)
3144 {
3145         ast_bridge_hook_callback hook_cb = (ast_bridge_hook_callback) callback;
3146
3147         return bridge_other_hook(features, hook_cb, hook_pvt, destructor, remove_flags,
3148                 AST_BRIDGE_HOOK_TYPE_MOVE);
3149 }
3150
3151 int ast_bridge_interval_hook(struct ast_bridge_features *features,
3152         enum ast_bridge_hook_timer_option flags,
3153         unsigned int interval,
3154         ast_bridge_hook_callback callback,
3155         void *hook_pvt,
3156         ast_bridge_hook_pvt_destructor destructor,
3157         enum ast_bridge_hook_remove_flags remove_flags)
3158 {
3159         struct ast_bridge_hook_timer *hook;
3160         int res;
3161
3162         if (!features ||!interval || !callback) {
3163                 return -1;
3164         }
3165
3166         /* Allocate new hook and setup it's various variables */
3167         hook = (struct ast_bridge_hook_timer *) bridge_hook_generic(sizeof(*hook), callback,
3168                 hook_pvt, destructor, remove_flags);
3169         if (!hook) {
3170                 return -1;
3171         }
3172         hook->generic.type = AST_BRIDGE_HOOK_TYPE_TIMER;
3173         hook->timer.interval = interval;
3174         hook->timer.trip_time = ast_tvadd(ast_tvnow(), ast_samp2tv(interval, 1000));
3175         hook->timer.seqno = ast_atomic_fetchadd_int((int *) &features->interval_sequence, +1);
3176         hook->timer.flags = flags;
3177
3178         ast_debug(1, "Putting interval hook %p with interval %u in the heap on features %p\n",
3179                 hook, hook->timer.interval, features);
3180         ast_heap_wrlock(features->interval_hooks);
3181         res = ast_heap_push(features->interval_hooks, hook);
3182         ast_heap_unlock(features->interval_hooks);
3183         if (res) {
3184                 /*
3185                  * Could not push the hook into the heap
3186                  *
3187                  * Remove the hook_pvt destructor call from the hook since we
3188                  * are returning failure to install the hook.
3189                  */
3190                 hook->generic.destructor = NULL;
3191                 ao2_ref(hook, -1);
3192         }
3193
3194         return res ? -1 : 0;
3195 }
3196
3197 int ast_bridge_features_enable(struct ast_bridge_features *features,
3198         enum ast_bridge_builtin_feature feature,
3199         const char *dtmf,
3200         void *config,
3201         ast_bridge_hook_pvt_destructor destructor,
3202         enum ast_bridge_hook_remove_flags remove_flags)
3203 {
3204         if (ARRAY_LEN(builtin_features_handlers) <= feature
3205                 || !builtin_features_handlers[feature]) {
3206                 return -1;
3207         }
3208
3209         /* If no alternate DTMF stream was provided use the default one */
3210         if (ast_strlen_zero(dtmf)) {
3211                 dtmf = builtin_features_dtmf[feature];
3212                 /* If no DTMF is still available (ie: it has been disabled) then error out now */
3213                 if (ast_strlen_zero(dtmf)) {
3214                         ast_debug(1, "Failed to enable built in feature %u on %p, no DTMF string is available for it.\n",
3215                                 feature, features);
3216                         return -1;
3217                 }
3218         }
3219
3220         /*
3221          * The rest is basically pretty easy.  We create another hook
3222          * using the built in feature's DTMF callback.  Easy as pie.
3223          */
3224         return ast_bridge_dtmf_hook(features, dtmf, builtin_features_handlers[feature],
3225                 config, destructor, remove_flags);
3226 }
3227
3228 int ast_bridge_features_limits_construct(struct ast_bridge_features_limits *limits)
3229 {
3230         memset(limits, 0, sizeof(*limits));
3231
3232         if (ast_string_field_init(limits, 256)) {
3233                 return -1;
3234         }
3235
3236         return 0;
3237 }
3238
3239 void ast_bridge_features_limits_destroy(struct ast_bridge_features_limits *limits)
3240 {
3241         ast_string_field_free_memory(limits);
3242 }
3243
3244 int ast_bridge_features_set_limits(struct ast_bridge_features *features,
3245         struct ast_bridge_features_limits *limits,
3246         enum ast_bridge_hook_remove_flags remove_flags)
3247 {
3248         if (builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_LIMITS]) {
3249                 ast_bridge_builtin_set_limits_fn callback;
3250
3251                 callback = builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_LIMITS];
3252                 return callback(features, limits, remove_flags);
3253         }
3254
3255         ast_log(LOG_ERROR, "Attempted to set limits without an AST_BRIDGE_BUILTIN_INTERVAL_LIMITS callback registered.\n");
3256         return -1;
3257 }
3258
3259 void ast_bridge_features_set_flag(struct ast_bridge_features *features, unsigned int flag)
3260 {
3261         ast_set_flag(&features->feature_flags, flag);
3262         features->usable = 1;
3263 }
3264
3265 /*!
3266  * \internal
3267  * \brief ao2 object match hooks with appropriate remove_flags.
3268  * \since 12.0.0
3269  *
3270  * \param obj Feature hook object.
3271  * \param arg Removal flags
3272  * \param flags Not used
3273  *
3274  * \retval CMP_MATCH if hook's remove_flags match the removal flags set.
3275  * \retval 0 if not match.
3276  */
3277 static int hook_remove_match(void *obj, void *arg, int flags)
3278 {
3279         struct ast_bridge_hook *hook = obj;
3280         enum ast_bridge_hook_remove_flags *remove_flags = arg;
3281
3282         if (ast_test_flag(&hook->remove_flags, *remove_flags)) {
3283                 return CMP_MATCH;
3284         } else {
3285                 return 0;
3286         }
3287 }
3288
3289 /*!
3290  * \internal
3291  * \brief Remove all hooks with appropriate remove_flags in the container.
3292  * \since 12.0.0
3293  *
3294  * \param hooks Hooks container to work on.
3295  * \param remove_flags Determinator for whether hook is removed
3296  *
3297  * \return Nothing
3298  */
3299 static void hooks_remove_container(struct ao2_container *hooks, enum ast_bridge_hook_remove_flags remove_flags)
3300 {
3301         ao2_callback(hooks, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
3302                 hook_remove_match, &remove_flags);
3303 }
3304
3305 /*!
3306  * \internal
3307  * \brief Remove all hooks in the heap with appropriate remove_flags set.
3308  * \since 12.0.0
3309  *
3310  * \param hooks Hooks heap to work on.
3311  * \param remove_flags Determinator for whether hook is removed
3312  *
3313  * \return Nothing
3314  */
3315 static void hooks_remove_heap(struct ast_heap *hooks, enum ast_bridge_hook_remove_flags remove_flags)
3316 {
3317         struct ast_bridge_hook *hook;
3318         int changed;
3319
3320         ast_heap_wrlock(hooks);
3321         do {
3322                 int idx;
3323
3324                 changed = 0;
3325                 for (idx = ast_heap_size(hooks); idx; --idx) {
3326                         hook = ast_heap_peek(hooks, idx);
3327                         if (ast_test_flag(&hook->remove_flags, remove_flags)) {
3328                                 ast_heap_remove(hooks, hook);
3329                                 ao2_ref(hook, -1);
3330                                 changed = 1;
3331                         }
3332                 }
3333         } while (changed);
3334         ast_heap_unlock(hooks);
3335 }
3336
3337 void ast_bridge_features_remove(struct ast_bridge_features *features, enum ast_bridge_hook_remove_flags remove_flags)
3338 {
3339         hooks_remove_container(features->dtmf_hooks, remove_flags);
3340         hooks_remove_container(features->other_hooks, remove_flags);
3341         hooks_remove_heap(features->interval_hooks, remove_flags);
3342 }
3343
3344 static int interval_hook_time_cmp(void *a, void *b)
3345 {
3346         struct ast_bridge_hook_timer *hook_a = a;
3347         struct ast_bridge_hook_timer *hook_b = b;
3348         int cmp;
3349
3350         cmp = ast_tvcmp(hook_b->timer.trip_time, hook_a->timer.trip_time);
3351         if (cmp) {
3352                 return cmp;
3353         }
3354
3355         cmp = hook_b->timer.seqno - hook_a->timer.seqno;
3356         return cmp;
3357 }
3358
3359 /*!
3360  * \internal
3361  * \brief DTMF hook container sort comparison function.
3362  * \since 12.0.0
3363  *
3364  * \param obj_left pointer to the (user-defined part) of an object.
3365  * \param obj_right pointer to the (user-defined part) of an object.
3366  * \param flags flags from ao2_callback()
3367  *   OBJ_POINTER - if set, 'obj_right', is an object.
3368  *   OBJ_KEY - if set, 'obj_right', is a search key item that is not an object.
3369  *   OBJ_PARTIAL_KEY - if set, 'obj_right', is a partial search key item that is not an object.
3370  *
3371  * \retval <0 if obj_left < obj_right
3372  * \retval =0 if obj_left == obj_right
3373  * \retval >0 if obj_left > obj_right
3374  */
3375 static int bridge_dtmf_hook_sort(const void *obj_left, const void *obj_right, int flags)
3376 {
3377         const struct ast_bridge_hook_dtmf *hook_left = obj_left;
3378         const struct ast_bridge_hook_dtmf *hook_right = obj_right;
3379         const char *right_key = obj_right;
3380         int cmp;
3381
3382         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
3383         default:
3384         case OBJ_POINTER:
3385                 right_key = hook_right->dtmf.code;
3386                 /* Fall through */
3387         case OBJ_KEY:
3388                 cmp = strcasecmp(hook_left->dtmf.code, right_key);
3389                 break;
3390         case OBJ_PARTIAL_KEY:
3391                 cmp = strncasecmp(hook_left->dtmf.code, right_key, strlen(right_key));
3392                 break;
3393         }
3394         return cmp;
3395 }
3396
3397 /*! \brief Callback for merging hook ao2_containers */
3398 static int merge_container_cb(void *obj, void *data, int flags)