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