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