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