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