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