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