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