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