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