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