Update BUGBUG comment.
[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 /*
1415  * XXX ASTERISK-22366 this needs more work.  The channels need
1416  * to be made compatible again if the formats change. The
1417  * bridge_channel thread needs to monitor for this case.
1418  */
1419                 /* The channel we want to notify is still in a bridge. */
1420                 bridge->v_table->notify_masquerade(bridge, bridge_channel);
1421                 bridge_reconfigured(bridge, 1);
1422         }
1423         ast_bridge_unlock(bridge);
1424         ao2_ref(bridge_channel, -1);
1425 }
1426
1427 /*
1428  * XXX ASTERISK-21271 make ast_bridge_join() require features to be allocated just like ast_bridge_impart() and not expect the struct back.
1429  *
1430  * This change is really going to break ConfBridge.  All other
1431  * users are easily changed.  However, it is needed so the
1432  * bridging code can manipulate features on all channels
1433  * consistently no matter how they joined.
1434  *
1435  * Need to update the features parameter doxygen when this
1436  * change is made to be like ast_bridge_impart().
1437  */
1438 int ast_bridge_join(struct ast_bridge *bridge,
1439         struct ast_channel *chan,
1440         struct ast_channel *swap,
1441         struct ast_bridge_features *features,
1442         struct ast_bridge_tech_optimizations *tech_args,
1443         int pass_reference)
1444 {
1445         struct ast_bridge_channel *bridge_channel;
1446         int res = 0;
1447
1448         bridge_channel = bridge_channel_internal_alloc(bridge);
1449         if (pass_reference) {
1450                 ao2_ref(bridge, -1);
1451         }
1452         if (!bridge_channel) {
1453                 res = -1;
1454                 goto join_exit;
1455         }
1456 /* 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. */
1457         ast_assert(features != NULL);
1458         if (!features) {
1459                 ao2_ref(bridge_channel, -1);
1460                 res = -1;
1461                 goto join_exit;
1462         }
1463         if (tech_args) {
1464                 bridge_channel->tech_args = *tech_args;
1465         }
1466
1467         ast_channel_lock(chan);
1468         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE)) {
1469                 res = -1;
1470         } else {
1471                 ast_channel_internal_bridge_channel_set(chan, bridge_channel);
1472         }
1473         ast_channel_unlock(chan);
1474         bridge_channel->thread = pthread_self();
1475         bridge_channel->chan = chan;
1476         bridge_channel->swap = swap;
1477         bridge_channel->features = features;
1478
1479         if (!res) {
1480                 res = bridge_channel_internal_join(bridge_channel);
1481         }
1482
1483         /* Cleanup all the data in the bridge channel after it leaves the bridge. */
1484         ast_channel_lock(chan);
1485         ast_channel_internal_bridge_channel_set(chan, NULL);
1486         ast_channel_unlock(chan);
1487         bridge_channel->chan = NULL;
1488         bridge_channel->swap = NULL;
1489         bridge_channel->features = NULL;
1490
1491         ao2_ref(bridge_channel, -1);
1492
1493 join_exit:;
1494         ast_bridge_run_after_callback(chan);
1495         if (!(ast_channel_softhangup_internal_flag(chan) & AST_SOFTHANGUP_ASYNCGOTO)
1496                 && !ast_bridge_setup_after_goto(chan)) {
1497                 /* Claim the after bridge goto is an async goto destination. */
1498                 ast_channel_lock(chan);
1499                 ast_softhangup_nolock(chan, AST_SOFTHANGUP_ASYNCGOTO);
1500                 ast_channel_unlock(chan);
1501         }
1502         return res;
1503 }
1504
1505 /*! \brief Thread responsible for imparted bridged channels to be departed */
1506 static void *bridge_channel_depart_thread(void *data)
1507 {
1508         struct ast_bridge_channel *bridge_channel = data;
1509
1510         if (bridge_channel->callid) {
1511                 ast_callid_threadassoc_add(bridge_channel->callid);
1512         }
1513
1514         bridge_channel_internal_join(bridge_channel);
1515
1516         /* cleanup */
1517         bridge_channel->swap = NULL;
1518         ast_bridge_features_destroy(bridge_channel->features);
1519         bridge_channel->features = NULL;
1520
1521         ast_bridge_discard_after_callback(bridge_channel->chan, AST_BRIDGE_AFTER_CB_REASON_DEPART);
1522         ast_bridge_discard_after_goto(bridge_channel->chan);
1523
1524         return NULL;
1525 }
1526
1527 /*! \brief Thread responsible for independent imparted bridged channels */
1528 static void *bridge_channel_ind_thread(void *data)
1529 {
1530         struct ast_bridge_channel *bridge_channel = data;
1531         struct ast_channel *chan;
1532
1533         if (bridge_channel->callid) {
1534                 ast_callid_threadassoc_add(bridge_channel->callid);
1535         }
1536
1537         bridge_channel_internal_join(bridge_channel);
1538         chan = bridge_channel->chan;
1539
1540         /* cleanup */
1541         ast_channel_lock(chan);
1542         ast_channel_internal_bridge_channel_set(chan, NULL);
1543         ast_channel_unlock(chan);
1544         bridge_channel->chan = NULL;
1545         bridge_channel->swap = NULL;
1546         ast_bridge_features_destroy(bridge_channel->features);
1547         bridge_channel->features = NULL;
1548
1549         ao2_ref(bridge_channel, -1);
1550
1551         ast_bridge_run_after_callback(chan);
1552         ast_bridge_run_after_goto(chan);
1553         return NULL;
1554 }
1555
1556 int ast_bridge_impart(struct ast_bridge *bridge, struct ast_channel *chan, struct ast_channel *swap, struct ast_bridge_features *features, int independent)
1557 {
1558         int res = 0;
1559         struct ast_bridge_channel *bridge_channel;
1560
1561         /* Imparted channels cannot have a PBX. */
1562         if (ast_channel_pbx(chan)) {
1563                 ast_log(AST_LOG_WARNING, "Channel %s has a PBX thread and cannot be imparted into bridge %s\n",
1564                         ast_channel_name(chan), bridge->uniqueid);
1565                 return -1;
1566         }
1567
1568         /* Supply an empty features structure if the caller did not. */
1569         if (!features) {
1570                 features = ast_bridge_features_new();
1571                 if (!features) {
1572                         return -1;
1573                 }
1574         }
1575
1576         /* Try to allocate a structure for the bridge channel */
1577         bridge_channel = bridge_channel_internal_alloc(bridge);
1578         if (!bridge_channel) {
1579                 ast_bridge_features_destroy(features);
1580                 return -1;
1581         }
1582
1583         ast_channel_lock(chan);
1584         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE)) {
1585                 ast_log(AST_LOG_NOTICE, "Channel %s is a zombie and cannot be imparted into bridge %s\n",
1586                         ast_channel_name(chan), bridge->uniqueid);
1587                 res = -1;
1588         } else {
1589                 ast_channel_internal_bridge_channel_set(chan, bridge_channel);
1590         }
1591         ast_channel_unlock(chan);
1592         bridge_channel->chan = chan;
1593         bridge_channel->swap = swap;
1594         bridge_channel->features = features;
1595         bridge_channel->depart_wait = independent ? 0 : 1;
1596         bridge_channel->callid = ast_read_threadstorage_callid();
1597
1598         /* Actually create the thread that will handle the channel */
1599         if (!res) {
1600                 if (independent) {
1601                         res = ast_pthread_create_detached(&bridge_channel->thread, NULL,
1602                                 bridge_channel_ind_thread, bridge_channel);
1603                 } else {
1604                         res = ast_pthread_create(&bridge_channel->thread, NULL,
1605                                 bridge_channel_depart_thread, bridge_channel);
1606                 }
1607         }
1608
1609         if (res) {
1610                 /* cleanup */
1611                 ast_channel_lock(chan);
1612                 ast_channel_internal_bridge_channel_set(chan, NULL);
1613                 ast_channel_unlock(chan);
1614                 bridge_channel->chan = NULL;
1615                 bridge_channel->swap = NULL;
1616                 ast_bridge_features_destroy(bridge_channel->features);
1617                 bridge_channel->features = NULL;
1618
1619                 ao2_ref(bridge_channel, -1);
1620                 return -1;
1621         }
1622
1623         return 0;
1624 }
1625
1626 int ast_bridge_depart(struct ast_channel *chan)
1627 {
1628         struct ast_bridge_channel *bridge_channel;
1629         int departable;
1630
1631         ast_channel_lock(chan);
1632         bridge_channel = ast_channel_internal_bridge_channel(chan);
1633         departable = bridge_channel && bridge_channel->depart_wait;
1634         ast_channel_unlock(chan);
1635         if (!departable) {
1636                 ast_log(LOG_ERROR, "Channel %s cannot be departed.\n",
1637                         ast_channel_name(chan));
1638                 /*
1639                  * Should never happen.  It likely means that
1640                  * ast_bridge_depart() is called by two threads for the same
1641                  * channel, the channel was never imparted to be departed, or it
1642                  * has already been departed.
1643                  */
1644                 ast_assert(0);
1645                 return -1;
1646         }
1647
1648         /*
1649          * We are claiming the reference held by the depart bridge
1650          * channel thread.
1651          */
1652
1653         ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
1654
1655         /* Wait for the depart thread to die */
1656         ast_debug(1, "Waiting for %p(%s) bridge thread to die.\n",
1657                 bridge_channel, ast_channel_name(bridge_channel->chan));
1658         pthread_join(bridge_channel->thread, NULL);
1659
1660         ast_channel_lock(chan);
1661         ast_channel_internal_bridge_channel_set(chan, NULL);
1662         ast_channel_unlock(chan);
1663
1664         /* We can get rid of the bridge_channel after the depart thread has died. */
1665         ao2_ref(bridge_channel, -1);
1666         return 0;
1667 }
1668
1669 int ast_bridge_remove(struct ast_bridge *bridge, struct ast_channel *chan)
1670 {
1671         struct ast_bridge_channel *bridge_channel;
1672
1673         ast_bridge_lock(bridge);
1674
1675         /* Try to find the channel that we want to remove */
1676         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
1677                 ast_bridge_unlock(bridge);
1678                 return -1;
1679         }
1680
1681         ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
1682
1683         ast_bridge_unlock(bridge);
1684
1685         return 0;
1686 }
1687
1688 static void kick_it(struct ast_bridge_channel *bridge_channel, const void *payload, size_t payload_size)
1689 {
1690         ast_bridge_channel_kick(bridge_channel);
1691 }
1692
1693 int ast_bridge_kick(struct ast_bridge *bridge, struct ast_channel *chan)
1694 {
1695         struct ast_bridge_channel *bridge_channel;
1696         int res;
1697
1698         ast_bridge_lock(bridge);
1699
1700         /* Try to find the channel that we want to kick. */
1701         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
1702                 ast_bridge_unlock(bridge);
1703                 return -1;
1704         }
1705
1706         res = ast_bridge_channel_queue_callback(bridge_channel, 0, kick_it, NULL, 0);
1707
1708         ast_bridge_unlock(bridge);
1709
1710         return res;
1711 }
1712
1713 /*!
1714  * \internal
1715  * \brief Point the bridge_channel to a new bridge.
1716  * \since 12.0.0
1717  *
1718  * \param bridge_channel What is to point to a new bridge.
1719  * \param new_bridge Where the bridge channel should point.
1720  *
1721  * \return Nothing
1722  */
1723 static void bridge_channel_change_bridge(struct ast_bridge_channel *bridge_channel, struct ast_bridge *new_bridge)
1724 {
1725         struct ast_bridge *old_bridge;
1726
1727         ao2_ref(new_bridge, +1);
1728         ast_bridge_channel_lock(bridge_channel);
1729         ast_channel_lock(bridge_channel->chan);
1730         old_bridge = bridge_channel->bridge;
1731         bridge_channel->bridge = new_bridge;
1732         ast_channel_internal_bridge_set(bridge_channel->chan, new_bridge);
1733         ast_channel_unlock(bridge_channel->chan);
1734         ast_bridge_channel_unlock(bridge_channel);
1735         ao2_ref(old_bridge, -1);
1736 }
1737
1738 void bridge_do_merge(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, struct ast_bridge_channel **kick_me, unsigned int num_kick,
1739         unsigned int optimized)
1740 {
1741         struct ast_bridge_channel *bridge_channel;
1742         unsigned int idx;
1743
1744         ast_debug(1, "Merging bridge %s into bridge %s\n",
1745                 src_bridge->uniqueid, dst_bridge->uniqueid);
1746
1747         ast_bridge_publish_merge(dst_bridge, src_bridge);
1748
1749         /*
1750          * Move channels from src_bridge over to dst_bridge.
1751          *
1752          * We must use AST_LIST_TRAVERSE_SAFE_BEGIN() because
1753          * bridge_channel_internal_pull() alters the list we are traversing.
1754          */
1755         AST_LIST_TRAVERSE_SAFE_BEGIN(&src_bridge->channels, bridge_channel, entry) {
1756                 if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1757                         /*
1758                          * The channel is already leaving let it leave normally because
1759                          * pulling it may delete hooks that should run for this channel.
1760                          */
1761                         continue;
1762                 }
1763                 if (ast_test_flag(&bridge_channel->features->feature_flags,
1764                         AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
1765                         continue;
1766                 }
1767
1768                 if (kick_me) {
1769                         for (idx = 0; idx < num_kick; ++idx) {
1770                                 if (bridge_channel == kick_me[idx]) {
1771                                         ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
1772                                         break;
1773                                 }
1774                         }
1775                 }
1776                 bridge_channel_internal_pull(bridge_channel);
1777                 if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1778                         /*
1779                          * The channel died as a result of being pulled or it was
1780                          * kicked.  Leave it pointing to the original bridge.
1781                          */
1782                         continue;
1783                 }
1784
1785                 /* Point to new bridge.*/
1786                 bridge_channel_change_bridge(bridge_channel, dst_bridge);
1787
1788                 if (bridge_channel_internal_push(bridge_channel)) {
1789                         ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
1790                 }
1791         }
1792         AST_LIST_TRAVERSE_SAFE_END;
1793
1794         if (kick_me) {
1795                 /*
1796                  * Now we can kick any channels in the dst_bridge without
1797                  * potentially dissolving the bridge.
1798                  */
1799                 for (idx = 0; idx < num_kick; ++idx) {
1800                         bridge_channel = kick_me[idx];
1801                         ast_bridge_channel_lock(bridge_channel);
1802                         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
1803                                 ast_bridge_channel_leave_bridge_nolock(bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
1804                                 bridge_channel_internal_pull(bridge_channel);
1805                         }
1806                         ast_bridge_channel_unlock(bridge_channel);
1807                 }
1808         }
1809
1810         bridge_reconfigured(dst_bridge, !optimized);
1811         bridge_reconfigured(src_bridge, !optimized);
1812
1813         ast_debug(1, "Merged bridge %s into bridge %s\n",
1814                 src_bridge->uniqueid, dst_bridge->uniqueid);
1815 }
1816
1817 struct merge_direction {
1818         /*! Destination merge bridge. */
1819         struct ast_bridge *dest;
1820         /*! Source merge bridge. */
1821         struct ast_bridge *src;
1822 };
1823
1824 /*!
1825  * \internal
1826  * \brief Determine which bridge should merge into the other.
1827  * \since 12.0.0
1828  *
1829  * \param bridge1 A bridge for merging
1830  * \param bridge2 A bridge for merging
1831  *
1832  * \note The two bridges are assumed already locked.
1833  *
1834  * \return Which bridge merges into which or NULL bridges if cannot merge.
1835  */
1836 static struct merge_direction bridge_merge_determine_direction(struct ast_bridge *bridge1, struct ast_bridge *bridge2)
1837 {
1838         struct merge_direction merge = { NULL, NULL };
1839         int bridge1_priority;
1840         int bridge2_priority;
1841
1842         if (!ast_test_flag(&bridge1->feature_flags,
1843                         AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)
1844                 && !ast_test_flag(&bridge2->feature_flags,
1845                         AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
1846                 /*
1847                  * Can merge either way.  Merge to the higher priority merge
1848                  * bridge.  Otherwise merge to the larger bridge.
1849                  */
1850                 bridge1_priority = bridge1->v_table->get_merge_priority(bridge1);
1851                 bridge2_priority = bridge2->v_table->get_merge_priority(bridge2);
1852                 if (bridge2_priority < bridge1_priority) {
1853                         merge.dest = bridge1;
1854                         merge.src = bridge2;
1855                 } else if (bridge1_priority < bridge2_priority) {
1856                         merge.dest = bridge2;
1857                         merge.src = bridge1;
1858                 } else {
1859                         /* Merge to the larger bridge. */
1860                         if (bridge2->num_channels <= bridge1->num_channels) {
1861                                 merge.dest = bridge1;
1862                                 merge.src = bridge2;
1863                         } else {
1864                                 merge.dest = bridge2;
1865                                 merge.src = bridge1;
1866                         }
1867                 }
1868         } else if (!ast_test_flag(&bridge1->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
1869                 && !ast_test_flag(&bridge2->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
1870                 /* Can merge only one way. */
1871                 merge.dest = bridge1;
1872                 merge.src = bridge2;
1873         } else if (!ast_test_flag(&bridge2->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
1874                 && !ast_test_flag(&bridge1->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
1875                 /* Can merge only one way. */
1876                 merge.dest = bridge2;
1877                 merge.src = bridge1;
1878         }
1879
1880         return merge;
1881 }
1882
1883 /*!
1884  * \internal
1885  * \brief Merge two bridges together
1886  * \since 12.0.0
1887  *
1888  * \param dst_bridge Destination bridge of merge.
1889  * \param src_bridge Source bridge of merge.
1890  * \param merge_best_direction TRUE if don't care about which bridge merges into the other.
1891  * \param kick_me Array of channels to kick from the bridges.
1892  * \param num_kick Number of channels in the kick_me array.
1893  *
1894  * \note The dst_bridge and src_bridge are assumed already locked.
1895  *
1896  * \retval 0 on success
1897  * \retval -1 on failure
1898  */
1899 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)
1900 {
1901         struct merge_direction merge;
1902         struct ast_bridge_channel **kick_them = NULL;
1903
1904         /* Sanity check. */
1905         ast_assert(dst_bridge && src_bridge && dst_bridge != src_bridge && (!num_kick || kick_me));
1906
1907         if (dst_bridge->dissolved || src_bridge->dissolved) {
1908                 ast_debug(1, "Can't merge bridges %s and %s, at least one bridge is dissolved.\n",
1909                         src_bridge->uniqueid, dst_bridge->uniqueid);
1910                 return -1;
1911         }
1912         if (ast_test_flag(&dst_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)
1913                 || ast_test_flag(&src_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
1914                 ast_debug(1, "Can't merge bridges %s and %s, masquerade only.\n",
1915                         src_bridge->uniqueid, dst_bridge->uniqueid);
1916                 return -1;
1917         }
1918         if (dst_bridge->inhibit_merge || src_bridge->inhibit_merge) {
1919                 ast_debug(1, "Can't merge bridges %s and %s, merging temporarily inhibited.\n",
1920                         src_bridge->uniqueid, dst_bridge->uniqueid);
1921                 return -1;
1922         }
1923
1924         if (merge_best_direction) {
1925                 merge = bridge_merge_determine_direction(dst_bridge, src_bridge);
1926         } else {
1927                 merge.dest = dst_bridge;
1928                 merge.src = src_bridge;
1929         }
1930
1931         if (!merge.dest
1932                 || ast_test_flag(&merge.dest->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
1933                 || ast_test_flag(&merge.src->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
1934                 ast_debug(1, "Can't merge bridges %s and %s, merging inhibited.\n",
1935                         src_bridge->uniqueid, dst_bridge->uniqueid);
1936                 return -1;
1937         }
1938         if (merge.src->num_channels < 2) {
1939                 /*
1940                  * For a two party bridge, a channel may be temporarily removed
1941                  * from the source bridge or the initial bridge members have not
1942                  * joined yet.
1943                  */
1944                 ast_debug(1, "Can't merge bridge %s into bridge %s, not enough channels in source bridge.\n",
1945                         merge.src->uniqueid, merge.dest->uniqueid);
1946                 return -1;
1947         }
1948         if (2 + num_kick < merge.dest->num_channels + merge.src->num_channels
1949                 && !(merge.dest->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)
1950                 && (!ast_test_flag(&merge.dest->feature_flags, AST_BRIDGE_FLAG_SMART)
1951                         || !(merge.dest->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX))) {
1952                 ast_debug(1, "Can't merge bridge %s into bridge %s, multimix is needed and it cannot be acquired.\n",
1953                         merge.src->uniqueid, merge.dest->uniqueid);
1954                 return -1;
1955         }
1956
1957         if (num_kick) {
1958                 unsigned int num_to_kick = 0;
1959                 unsigned int idx;
1960
1961                 kick_them = ast_alloca(num_kick * sizeof(*kick_them));
1962                 for (idx = 0; idx < num_kick; ++idx) {
1963                         kick_them[num_to_kick] = bridge_find_channel(merge.src, kick_me[idx]);
1964                         if (!kick_them[num_to_kick]) {
1965                                 kick_them[num_to_kick] = bridge_find_channel(merge.dest, kick_me[idx]);
1966                         }
1967                         if (kick_them[num_to_kick]) {
1968                                 ++num_to_kick;
1969                         }
1970                 }
1971
1972                 if (num_to_kick != num_kick) {
1973                         ast_debug(1, "Can't merge bridge %s into bridge %s, at least one kicked channel is not in either bridge.\n",
1974                                 merge.src->uniqueid, merge.dest->uniqueid);
1975                         return -1;
1976                 }
1977         }
1978
1979         bridge_do_merge(merge.dest, merge.src, kick_them, num_kick, 0);
1980         return 0;
1981 }
1982
1983 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)
1984 {
1985         int res;
1986
1987         /* Sanity check. */
1988         ast_assert(dst_bridge && src_bridge);
1989
1990         ast_bridge_lock_both(dst_bridge, src_bridge);
1991         res = bridge_merge_locked(dst_bridge, src_bridge, merge_best_direction, kick_me, num_kick);
1992         ast_bridge_unlock(src_bridge);
1993         ast_bridge_unlock(dst_bridge);
1994         return res;
1995 }
1996
1997 int bridge_do_move(struct ast_bridge *dst_bridge, struct ast_bridge_channel *bridge_channel, int attempt_recovery,
1998         unsigned int optimized)
1999 {
2000         struct ast_bridge *orig_bridge;
2001         int was_in_bridge;
2002         int res = 0;
2003
2004         if (bridge_channel->swap) {
2005                 ast_debug(1, "Moving %p(%s) into bridge %s swapping with %s\n",
2006                         bridge_channel, ast_channel_name(bridge_channel->chan), dst_bridge->uniqueid,
2007                         ast_channel_name(bridge_channel->swap));
2008         } else {
2009                 ast_debug(1, "Moving %p(%s) into bridge %s\n",
2010                         bridge_channel, ast_channel_name(bridge_channel->chan), dst_bridge->uniqueid);
2011         }
2012
2013         orig_bridge = bridge_channel->bridge;
2014         was_in_bridge = bridge_channel->in_bridge;
2015
2016         bridge_channel_internal_pull(bridge_channel);
2017         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2018                 /*
2019                  * The channel died as a result of being pulled.  Leave it
2020                  * pointing to the original bridge.
2021                  */
2022                 bridge_reconfigured(orig_bridge, 0);
2023                 return -1;
2024         }
2025
2026         /* Point to new bridge.*/
2027         ao2_ref(orig_bridge, +1);/* Keep a ref in case the push fails. */
2028         bridge_channel_change_bridge(bridge_channel, dst_bridge);
2029
2030         if (bridge_channel_internal_push(bridge_channel)) {
2031                 /* Try to put the channel back into the original bridge. */
2032                 if (attempt_recovery && was_in_bridge) {
2033                         /* Point back to original bridge. */
2034                         bridge_channel_change_bridge(bridge_channel, orig_bridge);
2035
2036                         if (bridge_channel_internal_push(bridge_channel)) {
2037                                 ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
2038                         }
2039                 } else {
2040                         ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
2041                 }
2042                 res = -1;
2043         }
2044
2045         bridge_reconfigured(dst_bridge, !optimized);
2046         bridge_reconfigured(orig_bridge, !optimized);
2047         ao2_ref(orig_bridge, -1);
2048         return res;
2049 }
2050
2051 /*!
2052  * \internal
2053  * \brief Move a channel from one bridge to another.
2054  * \since 12.0.0
2055  *
2056  * \param dst_bridge Destination bridge of bridge channel move.
2057  * \param src_bridge Source bridge of bridge channel move.
2058  * \param chan Channel to move.
2059  * \param swap Channel to replace in dst_bridge.
2060  * \param attempt_recovery TRUE if failure attempts to push channel back into original bridge.
2061  *
2062  * \note The dst_bridge and src_bridge are assumed already locked.
2063  *
2064  * \retval 0 on success.
2065  * \retval -1 on failure.
2066  */
2067 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)
2068 {
2069         struct ast_bridge_channel *bridge_channel;
2070
2071         if (dst_bridge->dissolved || src_bridge->dissolved) {
2072                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, at least one bridge is dissolved.\n",
2073                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2074                 return -1;
2075         }
2076         if (ast_test_flag(&dst_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)
2077                 || ast_test_flag(&src_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
2078                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, masquerade only.\n",
2079                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2080                 return -1;
2081         }
2082         if (dst_bridge->inhibit_merge || src_bridge->inhibit_merge) {
2083                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, temporarily inhibited.\n",
2084                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2085                 return -1;
2086         }
2087
2088         bridge_channel = bridge_find_channel(src_bridge, chan);
2089         if (!bridge_channel) {
2090                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel not in bridge.\n",
2091                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2092                 return -1;
2093         }
2094         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
2095                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel leaving bridge.\n",
2096                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2097                 return -1;
2098         }
2099         if (ast_test_flag(&bridge_channel->features->feature_flags,
2100                 AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
2101                 ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel immovable.\n",
2102                         ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
2103                 return -1;
2104         }
2105
2106         if (swap) {
2107                 struct ast_bridge_channel *bridge_channel_swap;
2108
2109                 bridge_channel_swap = bridge_find_channel(dst_bridge, swap);
2110                 if (!bridge_channel_swap) {
2111                         ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, swap channel %s not in bridge.\n",
2112                                 ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid,
2113                                 ast_channel_name(swap));
2114                         return -1;
2115                 }
2116                 if (bridge_channel_swap->state != BRIDGE_CHANNEL_STATE_WAIT) {
2117                         ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, swap channel %s leaving bridge.\n",
2118                                 ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid,
2119                                 ast_channel_name(swap));
2120                         return -1;
2121                 }
2122         }
2123
2124         bridge_channel->swap = swap;
2125         return bridge_do_move(dst_bridge, bridge_channel, attempt_recovery, 0);
2126 }
2127
2128 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)
2129 {
2130         int res;
2131
2132         ast_bridge_lock_both(dst_bridge, src_bridge);
2133         res = bridge_move_locked(dst_bridge, src_bridge, chan, swap, attempt_recovery);
2134         ast_bridge_unlock(src_bridge);
2135         ast_bridge_unlock(dst_bridge);
2136         return res;
2137 }
2138
2139 int ast_bridge_add_channel(struct ast_bridge *bridge, struct ast_channel *chan,
2140         struct ast_bridge_features *features, int play_tone, const char *xfersound)
2141 {
2142         RAII_VAR(struct ast_bridge *, chan_bridge, NULL, ao2_cleanup);
2143         RAII_VAR(struct ast_channel *, yanked_chan, NULL, ao2_cleanup);
2144
2145         ast_channel_lock(chan);
2146         chan_bridge = ast_channel_get_bridge(chan);
2147         ast_channel_unlock(chan);
2148
2149         if (chan_bridge) {
2150                 struct ast_bridge_channel *bridge_channel;
2151
2152                 ast_bridge_lock_both(bridge, chan_bridge);
2153                 bridge_channel = bridge_find_channel(chan_bridge, chan);
2154
2155                 if (bridge_move_locked(bridge, chan_bridge, chan, NULL, 1)) {
2156                         ast_bridge_unlock(chan_bridge);
2157                         ast_bridge_unlock(bridge);
2158                         return -1;
2159                 }
2160
2161                 /*
2162                  * bridge_move_locked() will implicitly ensure that
2163                  * bridge_channel is not NULL.
2164                  */
2165                 ast_assert(bridge_channel != NULL);
2166
2167                 /*
2168                  * Additional checks if the channel we just stole dissolves the
2169                  * original bridge.
2170                  */
2171                 bridge_dissolve_check_stolen(chan_bridge, bridge_channel);
2172                 ast_bridge_unlock(chan_bridge);
2173                 ast_bridge_unlock(bridge);
2174
2175                 /* The channel was in a bridge so it is not getting any new features. */
2176                 ast_bridge_features_destroy(features);
2177         } else {
2178                 /* Slightly less easy case. We need to yank channel A from
2179                  * where he currently is and impart him into our bridge.
2180                  */
2181                 yanked_chan = ast_channel_yank(chan);
2182                 if (!yanked_chan) {
2183                         ast_log(LOG_WARNING, "Could not gain control of channel %s\n", ast_channel_name(chan));
2184                         return -1;
2185                 }
2186                 if (ast_channel_state(yanked_chan) != AST_STATE_UP) {
2187                         ast_answer(yanked_chan);
2188                 }
2189                 ast_channel_ref(yanked_chan);
2190                 if (ast_bridge_impart(bridge, yanked_chan, NULL, features, 1)) {
2191                         /* It is possible for us to yank a channel and have some other
2192                          * thread start a PBX on the channl after we yanked it. In particular,
2193                          * this can theoretically happen on the ;2 of a Local channel if we
2194                          * yank it prior to the ;1 being answered. Make sure that it isn't
2195                          * executing a PBX before hanging it up.
2196                          */
2197                         if (ast_channel_pbx(yanked_chan)) {
2198                                 ast_channel_unref(yanked_chan);
2199                         } else {
2200                                 ast_hangup(yanked_chan);
2201                         }
2202                         return -1;
2203                 }
2204         }
2205
2206         if (play_tone && !ast_strlen_zero(xfersound)) {
2207                 struct ast_channel *play_chan = yanked_chan ?: chan;
2208                 RAII_VAR(struct ast_bridge_channel *, play_bridge_channel, NULL, ao2_cleanup);
2209
2210                 ast_channel_lock(play_chan);
2211                 play_bridge_channel = ast_channel_get_bridge_channel(play_chan);
2212                 ast_channel_unlock(play_chan);
2213
2214                 if (!play_bridge_channel) {
2215                         ast_log(LOG_WARNING, "Unable to play tone for channel %s. No longer in a bridge.\n",
2216                                 ast_channel_name(play_chan));
2217                 } else {
2218                         ast_bridge_channel_queue_playfile(play_bridge_channel, NULL, xfersound, NULL);
2219                 }
2220         }
2221         return 0;
2222 }
2223
2224 static int bridge_allows_optimization(struct ast_bridge *bridge)
2225 {
2226         return !(bridge->inhibit_merge
2227                 || bridge->dissolved
2228                 || ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY));
2229 }
2230
2231 /*!
2232  * \internal
2233  * \brief Lock the unreal channel stack for chan and prequalify it.
2234  * \since 12.0.0
2235  *
2236  * \param chan Unreal channel writing a frame into the channel driver.
2237  *
2238  * \note It is assumed that chan is already locked.
2239  *
2240  * \retval bridge on success with bridge and bridge_channel locked.
2241  * \retval NULL if cannot do optimization now.
2242  */
2243 static struct ast_bridge *optimize_lock_chan_stack(struct ast_channel *chan)
2244 {
2245         struct ast_bridge *bridge;
2246         struct ast_bridge_channel *bridge_channel;
2247
2248         if (!AST_LIST_EMPTY(ast_channel_readq(chan))) {
2249                 return NULL;
2250         }
2251         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF)) {
2252                 return NULL;
2253         }
2254         if (ast_channel_has_audio_frame_or_monitor(chan)) {
2255                 /* Channel has an active monitor, audiohook, or framehook. */
2256                 return NULL;
2257         }
2258         bridge_channel = ast_channel_internal_bridge_channel(chan);
2259         if (!bridge_channel || ast_bridge_channel_trylock(bridge_channel)) {
2260                 return NULL;
2261         }
2262         bridge = bridge_channel->bridge;
2263         if (bridge_channel->activity != BRIDGE_CHANNEL_THREAD_SIMPLE
2264                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2265                 || ast_bridge_trylock(bridge)) {
2266                 ast_bridge_channel_unlock(bridge_channel);
2267                 return NULL;
2268         }
2269         if (!bridge_channel_internal_allows_optimization(bridge_channel) ||
2270                         !bridge_allows_optimization(bridge)) {
2271                 ast_bridge_unlock(bridge);
2272                 ast_bridge_channel_unlock(bridge_channel);
2273                 return NULL;
2274         }
2275         return bridge;
2276 }
2277
2278 /*!
2279  * \internal
2280  * \brief Lock the unreal channel stack for peer and prequalify it.
2281  * \since 12.0.0
2282  *
2283  * \param peer Other unreal channel in the pair.
2284  *
2285  * \retval bridge on success with bridge, bridge_channel, and peer locked.
2286  * \retval NULL if cannot do optimization now.
2287  */
2288 static struct ast_bridge *optimize_lock_peer_stack(struct ast_channel *peer)
2289 {
2290         struct ast_bridge *bridge;
2291         struct ast_bridge_channel *bridge_channel;
2292
2293         if (ast_channel_trylock(peer)) {
2294                 return NULL;
2295         }
2296         if (!AST_LIST_EMPTY(ast_channel_readq(peer))) {
2297                 ast_channel_unlock(peer);
2298                 return NULL;
2299         }
2300         if (ast_test_flag(ast_channel_flags(peer), AST_FLAG_EMULATE_DTMF)) {
2301                 ast_channel_unlock(peer);
2302                 return NULL;
2303         }
2304         if (ast_channel_has_audio_frame_or_monitor(peer)) {
2305                 /* Peer has an active monitor, audiohook, or framehook. */
2306                 ast_channel_unlock(peer);
2307                 return NULL;
2308         }
2309         bridge_channel = ast_channel_internal_bridge_channel(peer);
2310         if (!bridge_channel || ast_bridge_channel_trylock(bridge_channel)) {
2311                 ast_channel_unlock(peer);
2312                 return NULL;
2313         }
2314         bridge = bridge_channel->bridge;
2315         if (bridge_channel->activity != BRIDGE_CHANNEL_THREAD_IDLE
2316                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
2317                 || ast_bridge_trylock(bridge)) {
2318                 ast_bridge_channel_unlock(bridge_channel);
2319                 ast_channel_unlock(peer);
2320                 return NULL;
2321         }
2322         if (!bridge_allows_optimization(bridge) ||
2323                         !bridge_channel_internal_allows_optimization(bridge_channel)) {
2324                 ast_bridge_unlock(bridge);
2325                 ast_bridge_channel_unlock(bridge_channel);
2326                 ast_channel_unlock(peer);
2327                 return NULL;
2328         }
2329         return bridge;
2330 }
2331
2332 /*!
2333  * \internal
2334  * \brief Indicates allowability of a swap optimization
2335  */
2336 enum bridge_allow_swap {
2337         /*! Bridges cannot allow for a swap optimization to occur */
2338         SWAP_PROHIBITED,
2339         /*! Bridge swap optimization can occur into the chan_bridge */
2340         SWAP_TO_CHAN_BRIDGE,
2341         /*! Bridge swap optimization can occur into the peer_bridge */
2342         SWAP_TO_PEER_BRIDGE,
2343 };
2344
2345 /*!
2346  * \internal
2347  * \brief Determine if two bridges allow for swap optimization to occur
2348  *
2349  * \param chan_bridge First bridge being tested
2350  * \param peer_bridge Second bridge being tested
2351  * \return Allowability of swap optimization
2352  */
2353 static enum bridge_allow_swap bridges_allow_swap_optimization(struct ast_bridge *chan_bridge,
2354                 struct ast_bridge *peer_bridge)
2355 {
2356         int chan_priority;
2357         int peer_priority;
2358
2359         if (!ast_test_flag(&chan_bridge->feature_flags,
2360                         AST_BRIDGE_FLAG_SWAP_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM |
2361                         AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2362                 && !ast_test_flag(&peer_bridge->feature_flags,
2363                         AST_BRIDGE_FLAG_SWAP_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM |
2364                         AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)) {
2365                 /*
2366                  * Can swap either way.  Swap to the higher priority merge
2367                  * bridge.
2368                  */
2369                 chan_priority = chan_bridge->v_table->get_merge_priority(chan_bridge);
2370                 peer_priority = peer_bridge->v_table->get_merge_priority(peer_bridge);
2371                 if (chan_bridge->num_channels == 2
2372                         && chan_priority <= peer_priority) {
2373                         return SWAP_TO_PEER_BRIDGE;
2374                 } else if (peer_bridge->num_channels == 2
2375                         && peer_priority <= chan_priority) {
2376                         return SWAP_TO_CHAN_BRIDGE;
2377                 }
2378         } else if (chan_bridge->num_channels == 2
2379                 && !ast_test_flag(&chan_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM | AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2380                 && !ast_test_flag(&peer_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_TO)) {
2381                 /* Can swap optimize only one way. */
2382                 return SWAP_TO_PEER_BRIDGE;
2383         } else if (peer_bridge->num_channels == 2
2384                 && !ast_test_flag(&peer_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM | AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
2385                 && !ast_test_flag(&chan_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_TO)) {
2386                 /* Can swap optimize only one way. */
2387                 return SWAP_TO_CHAN_BRIDGE;
2388         }
2389
2390         return SWAP_PROHIBITED;
2391 }
2392
2393 /*!
2394  * \internal
2395  * \brief Check and attempt to swap optimize out the unreal channels.
2396  * \since 12.0.0
2397  *
2398  * \param chan_bridge
2399  * \param chan_bridge_channel
2400  * \param peer_bridge
2401  * \param peer_bridge_channel
2402  * \param pvt Unreal data containing callbacks to call if the optimization actually
2403  * happens
2404  *
2405  * \retval 1 if unreal channels failed to optimize out.
2406  * \retval 0 if unreal channels were not optimized out.
2407  * \retval -1 if unreal channels were optimized out.
2408  */
2409 static int try_swap_optimize_out(struct ast_bridge *chan_bridge,
2410         struct ast_bridge_channel *chan_bridge_channel, struct ast_bridge *peer_bridge,
2411         struct ast_bridge_channel *peer_bridge_channel,
2412         struct ast_unreal_pvt *pvt)
2413 {
2414         struct ast_bridge *dst_bridge;
2415         struct ast_bridge_channel *dst_bridge_channel;
2416         struct ast_bridge_channel *src_bridge_channel;
2417         struct ast_bridge_channel *other;
2418         int res = 1;
2419
2420         switch (bridges_allow_swap_optimization(chan_bridge, peer_bridge)) {
2421         case SWAP_TO_CHAN_BRIDGE:
2422                 dst_bridge = chan_bridge;
2423                 dst_bridge_channel = chan_bridge_channel;
2424                 src_bridge_channel = peer_bridge_channel;
2425                 break;
2426         case SWAP_TO_PEER_BRIDGE:
2427                 dst_bridge = peer_bridge;
2428                 dst_bridge_channel = peer_bridge_channel;
2429                 src_bridge_channel = chan_bridge_channel;
2430                 break;
2431         case SWAP_PROHIBITED:
2432         default:
2433                 return 0;
2434         }
2435
2436         other = ast_bridge_channel_peer(src_bridge_channel);
2437         if (other && other->state == BRIDGE_CHANNEL_STATE_WAIT) {
2438                 ast_verb(3, "Move-swap optimizing %s <-- %s.\n",
2439                         ast_channel_name(dst_bridge_channel->chan),
2440                         ast_channel_name(other->chan));
2441
2442                 if (pvt && !ast_test_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN) && pvt->callbacks
2443                                 && pvt->callbacks->optimization_started) {
2444                         pvt->callbacks->optimization_started(pvt);
2445                         ast_set_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN);
2446                 }
2447                 other->swap = dst_bridge_channel->chan;
2448                 if (!bridge_do_move(dst_bridge, other, 1, 1)) {
2449                         ast_bridge_channel_leave_bridge(src_bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
2450                         res = -1;
2451                         if (pvt && pvt->callbacks && pvt->callbacks->optimization_finished) {
2452                                 pvt->callbacks->optimization_finished(pvt);
2453                         }
2454                 }
2455         }
2456         return res;
2457 }
2458
2459 /*!
2460  * \internal
2461  * \brief Indicates allowability of a merge optimization
2462  */
2463 enum bridge_allow_merge {
2464         /*! Bridge properties prohibit merge optimization */
2465         MERGE_PROHIBITED,
2466         /*! Merge optimization cannot occur because the source bridge has too few channels */
2467         MERGE_NOT_ENOUGH_CHANNELS,
2468         /*! Merge optimization cannot occur because multimix capability could not be requested */
2469         MERGE_NO_MULTIMIX,
2470         /*! Merge optimization allowed between bridges */
2471         MERGE_ALLOWED,
2472 };
2473
2474 /*!
2475  * \internal
2476  * \brief Determines allowability of a merge optimization
2477  *
2478  * \note The merge output parameter is undefined if MERGE_PROHIBITED is returned. For success
2479  * and other failure returns, a merge direction was determined, and the parameter is safe to
2480  * access.
2481  *
2482  * \param chan_bridge First bridge being tested
2483  * \param peer_bridge Second bridge being tested
2484  * \param num_kick_channels The number of channels to remove from the bridges during merging
2485  * \param[out] merge Indicates the recommended direction for the bridge merge
2486  */
2487 static enum bridge_allow_merge bridges_allow_merge_optimization(struct ast_bridge *chan_bridge,
2488                 struct ast_bridge *peer_bridge, int num_kick_channels, struct merge_direction *merge)
2489 {
2490         *merge = bridge_merge_determine_direction(chan_bridge, peer_bridge);
2491         if (!merge->dest) {
2492                 return MERGE_PROHIBITED;
2493         }
2494         if (merge->src->num_channels < 2) {
2495                 return MERGE_NOT_ENOUGH_CHANNELS;
2496         } else if ((2 + num_kick_channels) < merge->dest->num_channels + merge->src->num_channels
2497                 && !(merge->dest->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)
2498                 && (!ast_test_flag(&merge->dest->feature_flags, AST_BRIDGE_FLAG_SMART)
2499                         || !(merge->dest->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX))) {
2500                 return MERGE_NO_MULTIMIX;
2501         }
2502
2503         return MERGE_ALLOWED;
2504 }
2505
2506 /*!
2507  * \internal
2508  * \brief Check and attempt to merge optimize out the unreal channels.
2509  * \since 12.0.0
2510  *
2511  * \param chan_bridge
2512  * \param chan_bridge_channel
2513  * \param peer_bridge
2514  * \param peer_bridge_channel
2515  * \param pvt Unreal data containing callbacks to call if the optimization actually
2516  * happens
2517  *
2518  * \retval 0 if unreal channels were not optimized out.
2519  * \retval -1 if unreal channels were optimized out.
2520  */
2521 static int try_merge_optimize_out(struct ast_bridge *chan_bridge,
2522         struct ast_bridge_channel *chan_bridge_channel, struct ast_bridge *peer_bridge,
2523         struct ast_bridge_channel *peer_bridge_channel,
2524         struct ast_unreal_pvt *pvt)
2525 {
2526         struct merge_direction merge;
2527         struct ast_bridge_channel *kick_me[] = {
2528                 chan_bridge_channel,
2529                 peer_bridge_channel,
2530         };
2531
2532         switch (bridges_allow_merge_optimization(chan_bridge, peer_bridge, ARRAY_LEN(kick_me), &merge)) {
2533         case MERGE_ALLOWED:
2534                 break;
2535         case MERGE_PROHIBITED:
2536                 return 0;
2537         case MERGE_NOT_ENOUGH_CHANNELS:
2538                 ast_debug(4, "Can't optimize %s -- %s out, not enough channels in bridge %s.\n",
2539                         ast_channel_name(chan_bridge_channel->chan),
2540                         ast_channel_name(peer_bridge_channel->chan),
2541                         merge.src->uniqueid);
2542                 return 0;
2543         case MERGE_NO_MULTIMIX:
2544                 ast_debug(4, "Can't optimize %s -- %s out, multimix is needed and it cannot be acquired.\n",
2545                         ast_channel_name(chan_bridge_channel->chan),
2546                         ast_channel_name(peer_bridge_channel->chan));
2547                 return 0;
2548         }
2549
2550         ast_verb(3, "Merge optimizing %s -- %s out.\n",
2551                 ast_channel_name(chan_bridge_channel->chan),
2552                 ast_channel_name(peer_bridge_channel->chan));
2553
2554         if (pvt && !ast_test_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN) && pvt->callbacks
2555                         && pvt->callbacks->optimization_started) {
2556                 pvt->callbacks->optimization_started(pvt);
2557                 ast_set_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN);
2558         }
2559         bridge_do_merge(merge.dest, merge.src, kick_me, ARRAY_LEN(kick_me), 1);
2560         if (pvt && pvt->callbacks && pvt->callbacks->optimization_finished) {
2561                 pvt->callbacks->optimization_finished(pvt);
2562         }
2563
2564         return -1;
2565 }
2566
2567 int ast_bridge_unreal_optimize_out(struct ast_channel *chan, struct ast_channel *peer, struct ast_unreal_pvt *pvt)
2568 {
2569         struct ast_bridge *chan_bridge;
2570         struct ast_bridge *peer_bridge;
2571         struct ast_bridge_channel *chan_bridge_channel;
2572         struct ast_bridge_channel *peer_bridge_channel;
2573         int res = 0;
2574
2575         chan_bridge = optimize_lock_chan_stack(chan);
2576         if (!chan_bridge) {
2577                 return res;
2578         }
2579         chan_bridge_channel = ast_channel_internal_bridge_channel(chan);
2580
2581         peer_bridge = optimize_lock_peer_stack(peer);
2582         if (peer_bridge) {
2583                 peer_bridge_channel = ast_channel_internal_bridge_channel(peer);
2584
2585                 res = try_swap_optimize_out(chan_bridge, chan_bridge_channel,
2586                         peer_bridge, peer_bridge_channel, pvt);
2587                 if (!res) {
2588                         res = try_merge_optimize_out(chan_bridge, chan_bridge_channel,
2589                                 peer_bridge, peer_bridge_channel, pvt);
2590                 } else if (0 < res) {
2591                         res = 0;
2592                 }
2593
2594                 /* Release peer locks. */
2595                 ast_bridge_unlock(peer_bridge);
2596                 ast_bridge_channel_unlock(peer_bridge_channel);
2597                 ast_channel_unlock(peer);
2598         }
2599
2600         /* Release chan locks. */
2601         ast_bridge_unlock(chan_bridge);
2602         ast_bridge_channel_unlock(chan_bridge_channel);
2603
2604         return res;
2605 }
2606
2607 enum ast_bridge_optimization ast_bridges_allow_optimization(struct ast_bridge *chan_bridge,
2608                 struct ast_bridge *peer_bridge)
2609 {
2610         struct merge_direction merge;
2611
2612         if (!bridge_allows_optimization(chan_bridge) || !bridge_allows_optimization(peer_bridge)) {
2613                 return AST_BRIDGE_OPTIMIZE_PROHIBITED;
2614         }
2615
2616         switch (bridges_allow_swap_optimization(chan_bridge, peer_bridge)) {
2617         case SWAP_TO_CHAN_BRIDGE:
2618                 return AST_BRIDGE_OPTIMIZE_SWAP_TO_CHAN_BRIDGE;
2619         case SWAP_TO_PEER_BRIDGE:
2620                 return AST_BRIDGE_OPTIMIZE_SWAP_TO_PEER_BRIDGE;
2621         case SWAP_PROHIBITED:
2622         default:
2623                 break;
2624         }
2625
2626         /* Two channels will be kicked from the bridges, the unreal;1 and unreal;2 channels */
2627         if (bridges_allow_merge_optimization(chan_bridge, peer_bridge, 2, &merge) != MERGE_ALLOWED) {
2628                 return AST_BRIDGE_OPTIMIZE_PROHIBITED;
2629         }
2630
2631         if (merge.dest == chan_bridge) {
2632                 return AST_BRIDGE_OPTIMIZE_MERGE_TO_CHAN_BRIDGE;
2633         } else {
2634                 return AST_BRIDGE_OPTIMIZE_MERGE_TO_PEER_BRIDGE;
2635         }
2636 }
2637
2638 /*!
2639  * \internal
2640  * \brief Adjust the bridge merge inhibit request count.
2641  * \since 12.0.0
2642  *
2643  * \param bridge What to operate on.
2644  * \param request Inhibit request increment.
2645  *     (Positive to add requests.  Negative to remove requests.)
2646  *
2647  * \note This function assumes bridge is locked.
2648  *
2649  * \return Nothing
2650  */
2651 void bridge_merge_inhibit_nolock(struct ast_bridge *bridge, int request)
2652 {
2653         int new_request;
2654
2655         new_request = bridge->inhibit_merge + request;
2656         ast_assert(0 <= new_request);
2657         bridge->inhibit_merge = new_request;
2658 }
2659
2660 void ast_bridge_merge_inhibit(struct ast_bridge *bridge, int request)
2661 {
2662         ast_bridge_lock(bridge);
2663         bridge_merge_inhibit_nolock(bridge, request);
2664         ast_bridge_unlock(bridge);
2665 }
2666
2667 int ast_bridge_suspend(struct ast_bridge *bridge, struct ast_channel *chan)
2668 {
2669         struct ast_bridge_channel *bridge_channel;
2670 /* XXX ASTERISK-21271 the case of a disolved bridge while channel is suspended is not handled. */
2671 /* XXX ASTERISK-21271 suspend/unsuspend needs to be rethought. The caller must block until it has successfully suspended the channel for temporary control. */
2672 /* 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. */
2673
2674         ast_bridge_lock(bridge);
2675
2676         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
2677                 ast_bridge_unlock(bridge);
2678                 return -1;
2679         }
2680
2681         bridge_channel_internal_suspend_nolock(bridge_channel);
2682
2683         ast_bridge_unlock(bridge);
2684
2685         return 0;
2686 }
2687
2688 int ast_bridge_unsuspend(struct ast_bridge *bridge, struct ast_channel *chan)
2689 {
2690         struct ast_bridge_channel *bridge_channel;
2691 /* XXX ASTERISK-21271 the case of a disolved bridge while channel is suspended is not handled. */
2692
2693         ast_bridge_lock(bridge);
2694
2695         if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
2696                 ast_bridge_unlock(bridge);
2697                 return -1;
2698         }
2699
2700         bridge_channel_internal_unsuspend_nolock(bridge_channel);
2701
2702         ast_bridge_unlock(bridge);
2703
2704         return 0;
2705 }
2706
2707 void ast_bridge_technology_suspend(struct ast_bridge_technology *technology)
2708 {
2709         technology->suspended = 1;
2710 }
2711
2712 void ast_bridge_technology_unsuspend(struct ast_bridge_technology *technology)
2713 {
2714         /*
2715          * XXX We may want the act of unsuspending a bridge technology
2716          * to prod all existing bridges to see if they should start
2717          * using it.
2718          */
2719         technology->suspended = 0;
2720 }
2721
2722 int ast_bridge_features_register(enum ast_bridge_builtin_feature feature, ast_bridge_hook_callback callback, const char *dtmf)
2723 {
2724         if (ARRAY_LEN(builtin_features_handlers) <= feature
2725                 || builtin_features_handlers[feature]) {
2726                 return -1;
2727         }
2728
2729         if (!ast_strlen_zero(dtmf)) {
2730                 ast_copy_string(builtin_features_dtmf[feature], dtmf, sizeof(builtin_features_dtmf[feature]));
2731         }
2732
2733         builtin_features_handlers[feature] = callback;
2734
2735         return 0;
2736 }
2737
2738 int ast_bridge_features_unregister(enum ast_bridge_builtin_feature feature)
2739 {
2740         if (ARRAY_LEN(builtin_features_handlers) <= feature
2741                 || !builtin_features_handlers[feature]) {
2742                 return -1;
2743         }
2744
2745         builtin_features_handlers[feature] = NULL;
2746
2747         return 0;
2748 }
2749
2750 int ast_bridge_features_do(enum ast_bridge_builtin_feature feature, struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2751 {
2752         ast_bridge_hook_callback callback;
2753
2754         if (ARRAY_LEN(builtin_features_handlers) <= feature) {
2755                 return -1;
2756         }
2757
2758         callback = builtin_features_handlers[feature];
2759         if (!callback) {
2760                 return -1;
2761         }
2762         callback(bridge_channel, hook_pvt);
2763
2764         return 0;
2765 }
2766
2767 int ast_bridge_interval_register(enum ast_bridge_builtin_interval interval, ast_bridge_builtin_set_limits_fn callback)
2768 {
2769         if (ARRAY_LEN(builtin_interval_handlers) <= interval
2770                 || builtin_interval_handlers[interval]) {
2771                 return -1;
2772         }
2773
2774         builtin_interval_handlers[interval] = callback;
2775
2776         return 0;
2777 }
2778
2779 int ast_bridge_interval_unregister(enum ast_bridge_builtin_interval interval)
2780 {
2781         if (ARRAY_LEN(builtin_interval_handlers) <= interval
2782                 || !builtin_interval_handlers[interval]) {
2783                 return -1;
2784         }
2785
2786         builtin_interval_handlers[interval] = NULL;
2787
2788         return 0;
2789
2790 }
2791
2792 /*!
2793  * \internal
2794  * \brief Bridge hook destructor.
2795  * \since 12.0.0
2796  *
2797  * \param vhook Object to destroy.
2798  *
2799  * \return Nothing
2800  */
2801 static void bridge_hook_destroy(void *vhook)
2802 {
2803         struct ast_bridge_hook *hook = vhook;
2804
2805         if (hook->destructor) {
2806                 hook->destructor(hook->hook_pvt);
2807         }
2808 }
2809
2810 /*!
2811  * \internal
2812  * \brief Allocate and setup a generic bridge hook.
2813  * \since 12.0.0
2814  *
2815  * \param size How big an object to allocate.
2816  * \param callback Function to execute upon activation
2817  * \param hook_pvt Unique data
2818  * \param destructor Optional destructor callback for hook_pvt data
2819  * \param remove_flags Dictates what situations the hook should be removed.
2820  *
2821  * \retval hook on success.
2822  * \retval NULL on error.
2823  */
2824 static struct ast_bridge_hook *bridge_hook_generic(size_t size,
2825         ast_bridge_hook_callback callback,
2826         void *hook_pvt,
2827         ast_bridge_hook_pvt_destructor destructor,
2828         enum ast_bridge_hook_remove_flags remove_flags)
2829 {
2830         struct ast_bridge_hook *hook;
2831
2832         /* Allocate new hook and setup it's basic variables */
2833         hook = ao2_alloc_options(size, bridge_hook_destroy, AO2_ALLOC_OPT_LOCK_NOLOCK);
2834         if (hook) {
2835                 hook->callback = callback;
2836                 hook->destructor = destructor;
2837                 hook->hook_pvt = hook_pvt;
2838                 ast_set_flag(&hook->remove_flags, remove_flags);
2839         }
2840
2841         return hook;
2842 }
2843
2844 int ast_bridge_dtmf_hook(struct ast_bridge_features *features,
2845         const char *dtmf,
2846         ast_bridge_hook_callback callback,
2847         void *hook_pvt,
2848         ast_bridge_hook_pvt_destructor destructor,
2849         enum ast_bridge_hook_remove_flags remove_flags)
2850 {
2851         struct ast_bridge_hook_dtmf *hook;
2852         int res;
2853
2854         /* Allocate new hook and setup it's various variables */
2855         hook = (struct ast_bridge_hook_dtmf *) bridge_hook_generic(sizeof(*hook), callback,
2856                 hook_pvt, destructor, remove_flags);
2857         if (!hook) {
2858                 return -1;
2859         }
2860         hook->generic.type = AST_BRIDGE_HOOK_TYPE_DTMF;
2861         ast_copy_string(hook->dtmf.code, dtmf, sizeof(hook->dtmf.code));
2862
2863         /* Once done we put it in the container. */
2864         res = ao2_link(features->dtmf_hooks, hook) ? 0 : -1;
2865         if (res) {
2866                 /*
2867                  * Could not link the hook into the container.
2868                  *
2869                  * Remove the hook_pvt destructor call from the hook since we
2870                  * are returning failure to install the hook.
2871                  */
2872                 hook->generic.destructor = NULL;
2873         }
2874         ao2_ref(hook, -1);
2875
2876         return res;
2877 }
2878
2879 /*!
2880  * \internal
2881  * \brief Attach an other hook to a bridge features structure
2882  *
2883  * \param features Bridge features structure
2884  * \param callback Function to execute upon activation
2885  * \param hook_pvt Unique data
2886  * \param destructor Optional destructor callback for hook_pvt data
2887  * \param remove_flags Dictates what situations the hook should be removed.
2888  * \param type What type of hook is being attached.
2889  *
2890  * \retval 0 on success
2891  * \retval -1 on failure (The caller must cleanup any hook_pvt resources.)
2892  */
2893 static int bridge_other_hook(struct ast_bridge_features *features,
2894         ast_bridge_hook_callback callback,
2895         void *hook_pvt,
2896         ast_bridge_hook_pvt_destructor destructor,
2897         enum ast_bridge_hook_remove_flags remove_flags,
2898         enum ast_bridge_hook_type type)
2899 {
2900         struct ast_bridge_hook *hook;
2901         int res;
2902
2903         /* Allocate new hook and setup it's various variables */
2904         hook = bridge_hook_generic(sizeof(*hook), callback, hook_pvt, destructor,
2905                 remove_flags);
2906         if (!hook) {
2907                 return -1;
2908         }
2909         hook->type = type;
2910
2911         /* Once done we put it in the container. */
2912         res = ao2_link(features->other_hooks, hook) ? 0 : -1;
2913         if (res) {
2914                 /*
2915                  * Could not link the hook into the container.
2916                  *
2917                  * Remove the hook_pvt destructor call from the hook since we
2918                  * are returning failure to install the hook.
2919                  */
2920                 hook->destructor = NULL;
2921         }
2922         ao2_ref(hook, -1);
2923
2924         return res;
2925 }
2926
2927 int ast_bridge_hangup_hook(struct ast_bridge_features *features,
2928         ast_bridge_hook_callback callback,
2929         void *hook_pvt,
2930         ast_bridge_hook_pvt_destructor destructor,
2931         enum ast_bridge_hook_remove_flags remove_flags)
2932 {
2933         return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
2934                 AST_BRIDGE_HOOK_TYPE_HANGUP);
2935 }
2936
2937 int ast_bridge_join_hook(struct ast_bridge_features *features,
2938         ast_bridge_hook_callback callback,
2939         void *hook_pvt,
2940         ast_bridge_hook_pvt_destructor destructor,
2941         enum ast_bridge_hook_remove_flags remove_flags)
2942 {
2943         return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
2944                 AST_BRIDGE_HOOK_TYPE_JOIN);
2945 }
2946
2947 int ast_bridge_leave_hook(struct ast_bridge_features *features,
2948         ast_bridge_hook_callback callback,
2949         void *hook_pvt,
2950         ast_bridge_hook_pvt_destructor destructor,
2951         enum ast_bridge_hook_remove_flags remove_flags)
2952 {
2953         return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
2954                 AST_BRIDGE_HOOK_TYPE_LEAVE);
2955 }
2956
2957 int ast_bridge_talk_detector_hook(struct ast_bridge_features *features,
2958         ast_bridge_talking_indicate_callback callback,
2959         void *hook_pvt,
2960         ast_bridge_hook_pvt_destructor destructor,
2961         enum ast_bridge_hook_remove_flags remove_flags)
2962 {
2963         ast_bridge_hook_callback hook_cb = (ast_bridge_hook_callback) callback;
2964
2965         return bridge_other_hook(features, hook_cb, hook_pvt, destructor, remove_flags,
2966                 AST_BRIDGE_HOOK_TYPE_TALK);
2967 }
2968
2969 int ast_bridge_interval_hook(struct ast_bridge_features *features,
2970         enum ast_bridge_hook_timer_option flags,
2971         unsigned int interval,
2972         ast_bridge_hook_callback callback,
2973         void *hook_pvt,
2974         ast_bridge_hook_pvt_destructor destructor,
2975         enum ast_bridge_hook_remove_flags remove_flags)
2976 {
2977         struct ast_bridge_hook_timer *hook;
2978         int res;
2979
2980         if (!features ||!interval || !callback) {
2981                 return -1;
2982         }
2983
2984         /* Allocate new hook and setup it's various variables */
2985         hook = (struct ast_bridge_hook_timer *) bridge_hook_generic(sizeof(*hook), callback,
2986                 hook_pvt, destructor, remove_flags);
2987         if (!hook) {
2988                 return -1;
2989         }
2990         hook->generic.type = AST_BRIDGE_HOOK_TYPE_TIMER;
2991         hook->timer.interval = interval;
2992         hook->timer.trip_time = ast_tvadd(ast_tvnow(), ast_samp2tv(interval, 1000));
2993         hook->timer.seqno = ast_atomic_fetchadd_int((int *) &features->interval_sequence, +1);
2994         hook->timer.flags = flags;
2995
2996         ast_debug(1, "Putting interval hook %p with interval %u in the heap on features %p\n",
2997                 hook, hook->timer.interval, features);
2998         ast_heap_wrlock(features->interval_hooks);
2999         res = ast_heap_push(features->interval_hooks, hook);
3000         ast_heap_unlock(features->interval_hooks);
3001         if (res) {
3002                 /*
3003                  * Could not push the hook into the heap
3004                  *
3005                  * Remove the hook_pvt destructor call from the hook since we
3006                  * are returning failure to install the hook.
3007                  */
3008                 hook->generic.destructor = NULL;
3009                 ao2_ref(hook, -1);
3010         }
3011
3012         return res ? -1 : 0;
3013 }
3014
3015 int ast_bridge_features_enable(struct ast_bridge_features *features,
3016         enum ast_bridge_builtin_feature feature,
3017         const char *dtmf,
3018         void *config,
3019         ast_bridge_hook_pvt_destructor destructor,
3020         enum ast_bridge_hook_remove_flags remove_flags)
3021 {
3022         if (ARRAY_LEN(builtin_features_handlers) <= feature
3023                 || !builtin_features_handlers[feature]) {
3024                 return -1;
3025         }
3026
3027         /* If no alternate DTMF stream was provided use the default one */
3028         if (ast_strlen_zero(dtmf)) {
3029                 dtmf = builtin_features_dtmf[feature];
3030                 /* If no DTMF is still available (ie: it has been disabled) then error out now */
3031                 if (ast_strlen_zero(dtmf)) {
3032                         ast_debug(1, "Failed to enable built in feature %d on %p, no DTMF string is available for it.\n",
3033                                 feature, features);
3034                         return -1;
3035                 }
3036         }
3037
3038         /*
3039          * The rest is basically pretty easy.  We create another hook
3040          * using the built in feature's DTMF callback.  Easy as pie.
3041          */
3042         return ast_bridge_dtmf_hook(features, dtmf, builtin_features_handlers[feature],
3043                 config, destructor, remove_flags);
3044 }
3045
3046 int ast_bridge_features_limits_construct(struct ast_bridge_features_limits *limits)
3047 {
3048         memset(limits, 0, sizeof(*limits));
3049
3050         if (ast_string_field_init(limits, 256)) {
3051                 return -1;
3052         }
3053
3054         return 0;
3055 }
3056
3057 void ast_bridge_features_limits_destroy(struct ast_bridge_features_limits *limits)
3058 {
3059         ast_string_field_free_memory(limits);
3060 }
3061
3062 int ast_bridge_features_set_limits(struct ast_bridge_features *features,
3063         struct ast_bridge_features_limits *limits,
3064         enum ast_bridge_hook_remove_flags remove_flags)
3065 {
3066         if (builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_LIMITS]) {
3067                 ast_bridge_builtin_set_limits_fn callback;
3068
3069                 callback = builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_LIMITS];
3070                 return callback(features, limits, remove_flags);
3071         }
3072
3073         ast_log(LOG_ERROR, "Attempted to set limits without an AST_BRIDGE_BUILTIN_INTERVAL_LIMITS callback registered.\n");
3074         return -1;
3075 }
3076
3077 void ast_bridge_features_set_flag(struct ast_bridge_features *features, unsigned int flag)
3078 {
3079         ast_set_flag(&features->feature_flags, flag);
3080         features->usable = 1;
3081 }
3082
3083 /*!
3084  * \internal
3085  * \brief ao2 object match hooks with appropriate remove_flags.
3086  * \since 12.0.0
3087  *
3088  * \param obj Feature hook object.
3089  * \param arg Removal flags
3090  * \param flags Not used
3091  *
3092  * \retval CMP_MATCH if hook's remove_flags match the removal flags set.
3093  * \retval 0 if not match.
3094  */
3095 static int hook_remove_match(void *obj, void *arg, int flags)
3096 {
3097         struct ast_bridge_hook *hook = obj;
3098         enum ast_bridge_hook_remove_flags *remove_flags = arg;
3099
3100         if (ast_test_flag(&hook->remove_flags, *remove_flags)) {
3101                 return CMP_MATCH;
3102         } else {
3103                 return 0;
3104         }
3105 }
3106
3107 /*!
3108  * \internal
3109  * \brief Remove all hooks with appropriate remove_flags in the container.
3110  * \since 12.0.0
3111  *
3112  * \param hooks Hooks container to work on.
3113  * \param remove_flags Determinator for whether hook is removed
3114  *
3115  * \return Nothing
3116  */
3117 static void hooks_remove_container(struct ao2_container *hooks, enum ast_bridge_hook_remove_flags remove_flags)
3118 {
3119         ao2_callback(hooks, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
3120                 hook_remove_match, &remove_flags);
3121 }
3122
3123 /*!
3124  * \internal
3125  * \brief Remove all hooks in the heap with appropriate remove_flags set.
3126  * \since 12.0.0
3127  *
3128  * \param hooks Hooks heap to work on.
3129  * \param remove_flags Determinator for whether hook is removed
3130  *
3131  * \return Nothing
3132  */
3133 static void hooks_remove_heap(struct ast_heap *hooks, enum ast_bridge_hook_remove_flags remove_flags)
3134 {
3135         struct ast_bridge_hook *hook;
3136         int changed;
3137
3138         ast_heap_wrlock(hooks);
3139         do {
3140                 int idx;
3141
3142                 changed = 0;
3143                 for (idx = ast_heap_size(hooks); idx; --idx) {
3144                         hook = ast_heap_peek(hooks, idx);
3145                         if (ast_test_flag(&hook->remove_flags, remove_flags)) {
3146                                 ast_heap_remove(hooks, hook);
3147                                 ao2_ref(hook, -1);
3148                                 changed = 1;
3149                         }
3150                 }
3151         } while (changed);
3152         ast_heap_unlock(hooks);
3153 }
3154
3155 void ast_bridge_features_remove(struct ast_bridge_features *features, enum ast_bridge_hook_remove_flags remove_flags)
3156 {
3157         hooks_remove_container(features->dtmf_hooks, remove_flags);
3158         hooks_remove_container(features->other_hooks, remove_flags);
3159         hooks_remove_heap(features->interval_hooks, remove_flags);
3160 }
3161
3162 static int interval_hook_time_cmp(void *a, void *b)
3163 {
3164         struct ast_bridge_hook_timer *hook_a = a;
3165         struct ast_bridge_hook_timer *hook_b = b;
3166         int cmp;
3167
3168         cmp = ast_tvcmp(hook_b->timer.trip_time, hook_a->timer.trip_time);
3169         if (cmp) {
3170                 return cmp;
3171         }
3172
3173         cmp = hook_b->timer.seqno - hook_a->timer.seqno;
3174         return cmp;
3175 }
3176
3177 /*!
3178  * \internal
3179  * \brief DTMF hook container sort comparison function.
3180  * \since 12.0.0
3181  *
3182  * \param obj_left pointer to the (user-defined part) of an object.
3183  * \param obj_right pointer to the (user-defined part) of an object.
3184  * \param flags flags from ao2_callback()
3185  *   OBJ_POINTER - if set, 'obj_right', is an object.
3186  *   OBJ_KEY - if set, 'obj_right', is a search key item that is not an object.
3187  *   OBJ_PARTIAL_KEY - if set, 'obj_right', is a partial search key item that is not an object.
3188  *
3189  * \retval <0 if obj_left < obj_right
3190  * \retval =0 if obj_left == obj_right
3191  * \retval >0 if obj_left > obj_right
3192  */
3193 static int bridge_dtmf_hook_sort(const void *obj_left, const void *obj_right, int flags)
3194 {
3195         const struct ast_bridge_hook_dtmf *hook_left = obj_left;
3196         const struct ast_bridge_hook_dtmf *hook_right = obj_right;
3197         const char *right_key = obj_right;
3198         int cmp;
3199
3200         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
3201         default:
3202         case OBJ_POINTER:
3203                 right_key = hook_right->dtmf.code;
3204                 /* Fall through */
3205         case OBJ_KEY:
3206                 cmp = strcasecmp(hook_left->dtmf.code, right_key);
3207                 break;
3208         case OBJ_PARTIAL_KEY:
3209                 cmp = strncasecmp(hook_left->dtmf.code, right_key, strlen(right_key));
3210                 break;
3211         }
3212         return cmp;
3213 }
3214
3215 /* XXX ASTERISK-21271 make ast_bridge_features_init() static when make ast_bridge_join() requires features to be allocated. */
3216 int ast_bridge_features_init(struct ast_bridge_features *features)
3217 {
3218         /* Zero out the structure */
3219         memset(features, 0, sizeof(*features));
3220
3221         /* Initialize the DTMF hooks container */
3222         features->dtmf_hooks = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX,
3223                 AO2_CONTAINER_ALLOC_OPT_DUPS_REPLACE, bridge_dtmf_hook_sort, NULL);
3224         if (!features->dtmf_hooks) {
3225                 return -1;
3226         }
3227
3228         /* Initialize the miscellaneous other hooks container */
3229         features->other_hooks = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL,
3230                 NULL);
3231         if (!features->other_hooks) {
3232                 return -1;
3233         }
3234
3235         /* Initialize the interval hooks heap */
3236         features->interval_hooks = ast_heap_create(8, interval_hook_time_cmp,
3237                 offsetof(struct ast_bridge_hook_timer, timer.heap_index));
3238         if (!features->interval_hooks) {
3239                 return -1;
3240         }
3241
3242         features->dtmf_passthrough = 1;
3243
3244         return 0;
3245 }
3246
3247 /* XXX ASTERISK-21271 make ast_bridge_features_cleanup() static when make ast_bridge_join() requires features to be allocated. */
3248 void ast_bridge_features_cleanup(struct ast_bridge_features *features)
3249 {
3250         struct ast_bridge_hook_timer *hook;
3251
3252         /* Destroy the interval hooks heap. */
3253         if (features->interval_hooks) {
3254                 while ((hook = ast_heap_pop(features->interval_hooks))) {
3255                         ao2_ref(hook, -1);
3256                 }
3257                 features->interval_hooks = ast_heap_destroy(features->interval_hooks);
3258         }
3259
3260         /* Destroy the miscellaneous other hooks container. */
3261         ao2_cleanup(features->other_hooks);
3262         features->other_hooks = NULL;
3263
3264         /* Destroy the DTMF hooks container. */
3265         ao2_cleanup(features->dtmf_hooks);
3266         features->dtmf_hooks = NULL;
3267 }
3268
3269 void ast_bridge_features_destroy(struct ast_bridge_features *features)
3270 {
3271         if (!features) {
3272                 return;
3273         }
3274         ast_bridge_features_cleanup(features);
3275         ast_free(features);
3276 }
3277
3278 struct ast_bridge_features *ast_bridge_features_new(void)
3279 {
3280         struct ast_bridge_features *features;
3281
3282         features = ast_malloc(sizeof(*features));
3283         if (features) {
3284                 if (ast_bridge_features_init(features)) {
3285                         ast_bridge_features_destroy(features);
3286                         features = NULL;
3287                 }
3288         }
3289
3290         return features;
3291 }
3292
3293 void ast_bridge_set_mixing_interval(struct ast_bridge *bridge, unsigned int mixing_interval)
3294 {
3295         ast_bridge_lock(bridge);
3296         bridge->softmix.internal_mixing_interval = mixing_interval;
3297         ast_bridge_unlock(bridge);
3298 }
3299
3300 void ast_bridge_set_internal_sample_rate(struct ast_bridge *bridge, unsigned int sample_rate)
3301 {
3302         ast_bridge_lock(bridge);
3303         bridge->softmix.internal_sample_rate = sample_rate;
3304         ast_bridge_unlock(bridge);
3305 }
3306
3307 static void cleanup_video_mode(struct ast_bridge *bridge)
3308 {
3309         switch (bridge->softmix.video_mode.mode) {
3310         case AST_BRIDGE_VIDEO_MODE_NONE:
3311                 break;
3312         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3313                 if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc) {
3314                         ast_channel_unref(bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc);
3315                 }
3316                 break;
3317         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3318                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc) {
3319                         ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc);
3320                 }
3321                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc) {
3322                         ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc);
3323                 }
3324         }
3325         memset(&bridge->softmix.video_mode, 0, sizeof(bridge->softmix.video_mode));
3326 }
3327
3328 void ast_bridge_set_single_src_video_mode(struct ast_bridge *bridge, struct ast_channel *video_src_chan)
3329 {
3330         ast_bridge_lock(bridge);
3331         cleanup_video_mode(bridge);
3332         bridge->softmix.video_mode.mode = AST_BRIDGE_VIDEO_MODE_SINGLE_SRC;
3333         bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc = ast_channel_ref(video_src_chan);
3334         ast_test_suite_event_notify("BRIDGE_VIDEO_MODE", "Message: video mode set to single source\r\nVideo Mode: %d\r\nVideo Channel: %s",
3335                 bridge->softmix.video_mode.mode, ast_channel_name(video_src_chan));
3336         ast_indicate(video_src_chan, AST_CONTROL_VIDUPDATE);
3337         ast_bridge_unlock(bridge);
3338 }
3339
3340 void ast_bridge_set_talker_src_video_mode(struct ast_bridge *bridge)
3341 {
3342         ast_bridge_lock(bridge);
3343         cleanup_video_mode(bridge);
3344         bridge->softmix.video_mode.mode = AST_BRIDGE_VIDEO_MODE_TALKER_SRC;
3345         ast_test_suite_event_notify("BRIDGE_VIDEO_MODE", "Message: video mode set to talker source\r\nVideo Mode: %d",
3346                 bridge->softmix.video_mode.mode);
3347         ast_bridge_unlock(bridge);
3348 }
3349
3350 void ast_bridge_update_talker_src_video_mode(struct ast_bridge *bridge, struct ast_channel *chan, int talker_energy, int is_keyframe)
3351 {
3352         struct ast_bridge_video_talker_src_data *data;
3353
3354         /* If the channel doesn't support video, we don't care about it */
3355         if (!ast_format_cap_has_type(ast_channel_nativeformats(chan), AST_FORMAT_TYPE_VIDEO)) {
3356                 return;
3357         }
3358
3359         ast_bridge_lock(bridge);
3360         data = &bridge->softmix.video_mode.mode_data.talker_src_data;
3361
3362         if (data->chan_vsrc == chan) {
3363                 data->average_talking_energy = talker_energy;
3364         } else if ((data->average_talking_energy < talker_energy) && is_keyframe) {
3365                 if (data->chan_old_vsrc) {
3366                         ast_channel_unref(data->chan_old_vsrc);
3367                 }
3368                 if (data->chan_vsrc) {
3369                         data->chan_old_vsrc = data->chan_vsrc;
3370                         ast_indicate(data->chan_old_vsrc, AST_CONTROL_VIDUPDATE);
3371                 }
3372                 data->chan_vsrc = ast_channel_ref(chan);
3373                 data->average_talking_energy = talker_energy;
3374                 ast_test_suite_event_notify("BRIDGE_VIDEO_SRC", "Message: video source updated\r\nVideo Channel: %s", ast_channel_name(data->chan_vsrc));
3375                 ast_indicate(data->chan_vsrc, AST_CONTROL_VIDUPDATE);
3376         } else if ((data->average_talking_energy < talker_energy) && !is_keyframe) {
3377                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
3378         } else if (!data->chan_vsrc && is_keyframe) {
3379                 data->chan_vsrc = ast_channel_ref(chan);
3380                 data->average_talking_energy = talker_energy;
3381                 ast_test_suite_event_notify("BRIDGE_VIDEO_SRC", "Message: video source updated\r\nVideo Channel: %s", ast_channel_name(data->chan_vsrc));
3382                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
3383         } else if (!data->chan_old_vsrc && is_keyframe) {
3384                 data->chan_old_vsrc = ast_channel_ref(chan);
3385                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
3386         }
3387         ast_bridge_unlock(bridge);
3388 }
3389
3390 int ast_bridge_number_video_src(struct ast_bridge *bridge)
3391 {
3392         int res = 0;
3393
3394         ast_bridge_lock(bridge);
3395         switch (bridge->softmix.video_mode.mode) {
3396         case AST_BRIDGE_VIDEO_MODE_NONE:
3397                 break;
3398         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3399                 if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc) {
3400                         res = 1;
3401                 }
3402                 break;
3403         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3404                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc) {
3405                         res++;
3406                 }
3407                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc) {
3408                         res++;
3409                 }
3410         }
3411         ast_bridge_unlock(bridge);
3412         return res;
3413 }
3414
3415 int ast_bridge_is_video_src(struct ast_bridge *bridge, struct ast_channel *chan)
3416 {
3417         int res = 0;
3418
3419         ast_bridge_lock(bridge);
3420         switch (bridge->softmix.video_mode.mode) {
3421         case AST_BRIDGE_VIDEO_MODE_NONE:
3422                 break;
3423         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3424                 if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc == chan) {
3425                         res = 1;
3426                 }
3427                 break;
3428         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3429                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc == chan) {
3430                         res = 1;
3431                 } else if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc == chan) {
3432                         res = 2;
3433                 }
3434
3435         }
3436         ast_bridge_unlock(bridge);
3437         return res;
3438 }
3439
3440 void ast_bridge_remove_video_src(struct ast_bridge *bridge, struct ast_channel *chan)
3441 {
3442         ast_bridge_lock(bridge);
3443         switch (bridge->softmix.video_mode.mode) {
3444         case AST_BRIDGE_VIDEO_MODE_NONE:
3445                 break;
3446         case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
3447                 if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc == chan) {
3448                         if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc) {
3449                                 ast_channel_unref(bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc);
3450                         }
3451                         bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc = NULL;
3452                 }
3453                 break;
3454         case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
3455                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc == chan) {
3456                         if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc) {
3457                                 ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc);
3458                         }
3459                         bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc = NULL;
3460                         bridge->softmix.video_mode.mode_data.talker_src_data.average_talking_energy = 0;
3461                 }
3462                 if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc == chan) {
3463                         if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc) {
3464                                 ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc);
3465                         }
3466                         bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc = NULL;
3467                 }
3468         }
3469         ast_bridge_unlock(bridge);
3470 }
3471
3472 static int channel_hash(const void *obj, int flags)
3473 {
3474         const struct ast_channel *chan = obj;
3475         const char *name = obj;
3476         int hash;
3477
3478         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
3479         default:
3480         case OBJ_POINTER:
3481                 name = ast_channel_name(chan);
3482                 /* Fall through */
3483         case OBJ_KEY:
3484                 hash = ast_str_hash(name);
3485                 break;
3486         case OBJ_PARTIAL_KEY:
3487                 /* Should never happen in hash callback. */
3488                 ast_assert(0);
3489                 hash = 0;
3490                 break;
3491         }
3492         return hash;
3493 }
3494
3495 static int channel_cmp(void *obj, void *arg, int flags)
3496 {
3497         const struct ast_channel *left = obj;
3498         const struct ast_channel *right = arg;
3499         const char *right_name = arg;
3500         int cmp;
3501
3502         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
3503         default:
3504         case OBJ_POINTER:
3505                 right_name = ast_channel_name(right);
3506                 /* Fall through */
3507         case OBJ_KEY:
3508                 cmp = strcmp(ast_channel_name(left), right_name);
3509                 break;
3510         case OBJ_PARTIAL_KEY:
3511                 cmp = strncmp(ast_channel_name(left), right_name, strlen(right_name));
3512                 break;
3513         }
3514         return cmp ? 0 : CMP_MATCH;
3515 }
3516
3517 struct ao2_container *ast_bridge_peers_nolock(struct ast_bridge *bridge)
3518 {
3519         struct ao2_container *channels;
3520         struct ast_bridge_channel *iter;
3521
3522         channels = ao2_container_alloc_options(AO2_ALLOC_OPT_LOCK_NOLOCK,
3523                 13, channel_hash, channel_cmp);
3524         if (!channels) {
3525                 return NULL;
3526         }
3527
3528         AST_LIST_TRAVERSE(&bridge->channels, iter, entry) {
3529                 ao2_link(channels, iter->chan);
3530         }
3531
3532         return channels;
3533 }
3534
3535 struct ao2_container *ast_bridge_peers(struct ast_bridge *bridge)
3536 {
3537         struct ao2_container *channels;
3538
3539         ast_bridge_lock(bridge);
3540         channels = ast_bridge_peers_nolock(bridge);
3541         ast_bridge_unlock(bridge);
3542
3543         return channels;
3544 }
3545
3546 struct ast_channel *ast_bridge_peer_nolock(struct ast_bridge *bridge, struct ast_channel *chan)
3547 {
3548         struct ast_channel *peer = NULL;
3549         struct ast_bridge_channel *iter;
3550
3551         /* Asking for the peer channel only makes sense on a two-party bridge. */
3552         if (bridge->num_channels == 2
3553                 && bridge->technology->capabilities
3554                         & (AST_BRIDGE_CAPABILITY_NATIVE | AST_BRIDGE_CAPABILITY_1TO1MIX)) {
3555                 int in_bridge = 0;
3556
3557                 AST_LIST_TRAVERSE(&bridge->channels, iter, entry) {
3558                         if (iter->chan != chan) {
3559                                 peer = iter->chan;
3560                         } else {
3561                                 in_bridge = 1;
3562                         }
3563                 }
3564                 if (in_bridge && peer) {
3565                         ast_channel_ref(peer);
3566                 } else {
3567                         peer = NULL;
3568                 }
3569         }
3570
3571         return peer;
3572 }
3573
3574 struct ast_channel *ast_bridge_peer(struct ast_bridge *bridge, struct ast_channel *chan)
3575 {
3576         struct ast_channel *peer;
3577
3578         ast_bridge_lock(bridge);
3579         peer = ast_bridge_peer_nolock(bridge, chan);
3580         ast_bridge_unlock(bridge);
3581
3582         return peer;
3583 }
3584
3585 /*!
3586  * \internal
3587  * \brief Transfer an entire bridge to a specific destination.
3588  *
3589  * This creates a local channel to dial out and swaps the called local channel
3590  * with the transferer channel. By doing so, all participants in the bridge are
3591  * connected to the specified destination.
3592  *
3593  * While this means of transferring would work for both two-party and multi-party
3594  * bridges, this method is only used for multi-party bridges since this method would
3595  * be less efficient for two-party bridges.
3596  *
3597  * \param transferer The channel performing a transfer
3598  * \param bridge The bridge where the transfer is being performed
3599  * \param exten The destination extension for the blind transfer
3600  * \param context The destination context for the blind transfer
3601  * \param hook Framehook to attach to local channel
3602  * \return The success or failure of the operation
3603  */
3604 static enum ast_transfer_result blind_transfer_bridge(struct ast_channel *transferer,
3605                 struct ast_bridge *bridge, const char *exten, const char *context,
3606                 transfer_channel_cb new_channel_cb, void *user_data)
3607 {
3608         struct ast_channel *local;
3609         char chan_name[AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2];
3610         int cause;
3611
3612         snprintf(chan_name, sizeof(chan_name), "%s@%s", exten, context);
3613         local = ast_request("Local", ast_channel_nativeformats(transferer), transferer,
3614                         chan_name, &cause);
3615         if (!local) {
3616                 return AST_BRIDGE_TRANSFER_FAIL;
3617         }
3618
3619         if (new_channel_cb) {
3620                 new_channel_cb(local, user_data, AST_BRIDGE_TRANSFER_MULTI_PARTY);
3621         }
3622
3623         if (ast_call(local, chan_name, 0)) {
3624                 ast_hangup(local);
3625                 return AST_BRIDGE_TRANSFER_FAIL;
3626         }
3627         if (ast_bridge_impart(bridge, local, transferer, NULL, 1)) {
3628                 ast_hangup(local);
3629                 return AST_BRIDGE_TRANSFER_FAIL;
3630         }
3631         return AST_BRIDGE_TRANSFER_SUCCESS;
3632 }
3633
3634 /*!
3635  * \internal
3636  * \brief Base data to publish for stasis attended transfer messages
3637  */
3638 struct stasis_attended_transfer_publish_data {
3639         /* The bridge between the transferer and transferee, and the transferer channel in this bridge */
3640         struct ast_bridge_channel_pair to_transferee;
3641         /* The bridge between the transferer and transfer target, and the transferer channel in this bridge */
3642         struct ast_bridge_channel_pair to_transfer_target;
3643 };
3644
3645 static void stasis_publish_data_cleanup(struct stasis_attended_transfer_publish_data *publication)
3646 {
3647         ast_channel_unref(publication->to_transferee.channel);
3648         ast_channel_unref(publication->to_transfer_target.channel);
3649         ao2_cleanup(publication->to_transferee.bridge);
3650         ao2_cleanup(publication->to_transfer_target.bridge);
3651 }
3652
3653 /*!
3654  * \internal
3655  * \brief Set up base data for an attended transfer stasis publication
3656  *
3657  * \param to_transferee The original transferer channel, which may be bridged to a transferee
3658  * \param to_transferee_bridge The bridge that to_transferee is in.
3659  * \param to_transfer_target The second transferer channel, which may be bridged to a transfer target
3660  * \param to_target_bridge The bridge that to_transfer_target_is in.
3661  * \param[out] publication A structure to hold the other parameters
3662  */
3663 static void stasis_publish_data_init(struct ast_channel *to_transferee,
3664                 struct ast_bridge *to_transferee_bridge, struct ast_channel *to_transfer_target,
3665                 struct ast_bridge *to_target_bridge,
3666                 struct stasis_attended_transfer_publish_data *publication)
3667 {
3668         memset(publication, 0, sizeof(*publication));
3669         publication->to_transferee.channel = ast_channel_ref(to_transferee);
3670         if (to_transferee_bridge) {
3671                 ao2_ref(to_transferee_bridge, +1);
3672                 publication->to_transferee.bridge = to_transferee_bridge;
3673         }
3674
3675         publication->to_transfer_target.channel = ast_channel_ref(to_transfer_target);
3676         if (to_target_bridge) {
3677                 ao2_ref(to_target_bridge, +1);
3678                 publication->to_transfer_target.bridge = to_target_bridge;
3679         }
3680 }
3681
3682 /*
3683  * \internal
3684  * \brief Publish a stasis attended transfer resulting in a bridge merge
3685  *
3686  * \param publication Base data about the attended transfer
3687  * \param final_bridge The surviving bridge of the attended transfer
3688  */
3689 static void publish_attended_transfer_bridge_merge(struct stasis_attended_transfer_publish_data *publication,
3690                 struct ast_bridge *final_bridge)
3691 {
3692         ast_bridge_publish_attended_transfer_bridge_merge(1, AST_BRIDGE_TRANSFER_SUCCESS,
3693                         &publication->to_transferee, &publication->to_transfer_target, final_bridge);
3694 }
3695
3696 /*
3697  * \internal
3698  * \brief Publish a stasis attended transfer to an application
3699  *
3700  * \param publication Base data about the attended transfer
3701  * \param app The app that is running at the conclusion of the transfer
3702  */
3703 static void publish_attended_transfer_app(struct stasis_attended_transfer_publish_data *publication,
3704                 const char *app)
3705 {
3706         ast_bridge_publish_attended_transfer_app(1, AST_BRIDGE_TRANSFER_SUCCESS,
3707                         &publication->to_transferee, &publication->to_transfer_target, app);
3708 }
3709
3710 /*
3711  * \internal
3712  * \brief Publish a stasis attended transfer showing a link between bridges
3713  *
3714  * \param publication Base data about the attended transfer
3715  * \param local_channel1 Local channel in the original bridge
3716  * \param local_channel2 Local channel in the second bridge
3717  */
3718 static void publish_attended_transfer_link(struct stasis_attended_transfer_publish_data *publication,
3719                 struct ast_channel *local_channel1, struct ast_channel *local_channel2)
3720 {
3721         struct ast_channel *locals[2] = { local_channel1, local_channel2 };
3722
3723         ast_bridge_publish_attended_transfer_link(1, AST_BRIDGE_TRANSFER_SUCCESS,
3724                         &publication->to_transferee, &publication->to_transfer_target, locals);
3725 }
3726
3727 /*
3728  * \internal
3729  * \brief Publish a stasis attended transfer failure
3730  *
3731  * \param publication Base data about the attended transfer
3732  * \param result The transfer result
3733  */
3734 static void publish_attended_transfer_fail(struct stasis_attended_transfer_publish_data *publication,
3735                 enum ast_transfer_result result)
3736 {
3737         ast_bridge_publish_attended_transfer_fail(1, result, &publication->to_transferee,
3738                         &publication->to_transfer_target);
3739 }
3740
3741 /*!
3742  * \brief Perform an attended transfer of a bridge
3743  *
3744  * This performs an attended transfer of an entire bridge to a target.
3745  * The target varies, depending on what bridges exist during the transfer
3746  * attempt.
3747  *
3748  * If two bridges exist, then a local channel is created to link the two
3749  * bridges together.
3750  *
3751  * If only one bridge exists, then a local channel is created with one end
3752  * placed into the existing bridge and the other end masquerading into
3753  * the unbridged channel.
3754  *
3755  * \param chan1 Transferer channel. Guaranteed to be bridged.
3756  * \param chan2 Other transferer channel. May or may not be bridged.
3757  * \param bridge1 Bridge that chan1 is in. Guaranteed to be non-NULL.
3758  * \param bridge2 Bridge that chan2 is in. If NULL, then chan2 is not bridged.
3759  * \param publication Data to publish for a stasis attended transfer message.
3760  * \retval AST_BRIDGE_TRANSFER_FAIL Internal error occurred
3761  * \retval AST_BRIDGE_TRANSFER_SUCCESS Succesfully transferred the bridge
3762  */
3763 static enum ast_transfer_result attended_transfer_bridge(struct ast_channel *chan1,
3764                 struct ast_channel *chan2, struct ast_bridge *bridge1, struct ast_bridge *bridge2,
3765                 struct stasis_attended_transfer_publish_data *publication)
3766 {
3767         static const char *dest = "_attended@transfer/m";
3768         struct ast_channel *local_chan;
3769         int cause;
3770         int res;
3771         const char *app = NULL;
3772
3773         local_chan = ast_request("Local", ast_channel_nativeformats(chan1), chan1,
3774                         dest, &cause);
3775
3776         if (!local_chan) {
3777                 return AST_BRIDGE_TRANSFER_FAIL;
3778         }
3779
3780         if (bridge2) {
3781                 res = ast_local_setup_bridge(local_chan, bridge2, chan2, NULL);
3782         } else {
3783                 app = ast_strdupa(ast_channel_appl(chan2));
3784                 res = ast_local_setup_masquerade(local_chan, chan2);
3785         }
3786
3787         if (res) {
3788                 ast_hangup(local_chan);
3789                 return AST_BRIDGE_TRANSFER_FAIL;
3790         }
3791
3792         if (ast_call(local_chan, dest, 0)) {
3793                 ast_hangup(local_chan);
3794                 return AST_BRIDGE_TRANSFER_FAIL;
3795         }
3796
3797         if (ast_bridge_impart(bridge1, local_chan, chan1, NULL, 1)) {
3798                 ast_hangup(local_chan);
3799                 return AST_BRIDGE_TRANSFER_FAIL;
3800         }
3801
3802         if (bridge2) {
3803                 RAII_VAR(struct ast_channel *, local_chan2, NULL, ao2_cleanup);
3804
3805                 ast_channel_lock(local_chan);
3806                 local_chan2 = ast_local_get_peer(local_chan);
3807                 ast_channel_unlock(local_chan);
3808
3809                 ast_assert(local_chan2 != NULL);
3810
3811                 publish_attended_transfer_link(publication,
3812                                 local_chan, local_chan2);
3813         } else {
3814                 publish_attended_transfer_app(publication, app);
3815         }
3816         return AST_BRIDGE_TRANSFER_SUCCESS;
3817 }
3818
3819 /*!
3820  * \internal
3821  * \brief Get the transferee channel
3822  *
3823  * This is only applicable to cases where a transfer is occurring on a
3824  * two-party bridge. The channels container passed in is expected to only
3825  * contain two channels, the transferer and the transferee. The transferer
3826  * channel is passed in as a parameter to ensure we don't return it as
3827  * the transferee channel.
3828  *
3829  * \param channels A two-channel container containing the transferer and transferee
3830  * \param transferer The party that is transfering the call
3831  * \return The party that is being transferred
3832  */
3833 static struct ast_channel *get_transferee(struct ao2_container *channels, struct ast_channel *transferer)
3834 {
3835         struct ao2_iterator channel_iter;
3836         struct ast_channel *transferee;
3837
3838         for (channel_iter = ao2_iterator_init(channels, 0);
3839                         (transferee = ao2_iterator_next(&channel_iter));
3840                         ao2_cleanup(transferee)) {
3841                 if (transferee != transferer) {
3842                         break;
3843                 }
3844         }
3845
3846         ao2_iterator_destroy(&channel_iter);
3847         return transferee;
3848 }
3849
3850 static enum ast_transfer_result try_parking(struct ast_channel *transferer, const char *context, const char *exten)
3851 {
3852         RAII_VAR(struct ast_bridge_channel *, transferer_bridge_channel, NULL, ao2_cleanup);
3853
3854         if (!ast_parking_provider_registered()) {
3855                 return AST_BRIDGE_TRANSFER_FAIL;
3856         }
3857
3858         ast_channel_lock(transferer);
3859         transferer_bridge_channel = ast_channel_get_bridge_channel(transferer);
3860         ast_channel_unlock(transferer);
3861
3862         if (!transferer_bridge_channel) {
3863                 return AST_BRIDGE_TRANSFER_FAIL;
3864         }
3865
3866         if (ast_parking_blind_transfer_park(transferer_bridge_channel,
3867                 context, exten)) {
3868                 return AST_BRIDGE_TRANSFER_FAIL;
3869         }
3870
3871         return AST_BRIDGE_TRANSFER_SUCCESS;
3872 }
3873
3874 /*!
3875  * \internal
3876  * \brief Set the BLINDTRANSFER variable as appropriate on channels involved in the transfer
3877  *
3878  * The transferer channel will have its BLINDTRANSFER variable set the same as its BRIDGEPEER
3879  * variable. This will account for all channels that it is bridged to. The other channels
3880  * involved in the transfer will have their BLINDTRANSFER variable set to the transferer
3881  * channel's name.
3882  *
3883  * \param transferer The channel performing the blind transfer
3884  * \param channels The channels belonging to the bridge
3885  */
3886 static void set_blind_transfer_variables(struct ast_channel *transferer, struct ao2_container *channels)
3887 {
3888         struct ao2_iterator iter;
3889         struct ast_channel *chan;
3890         const char *transferer_name;
3891         const char *transferer_bridgepeer;
3892
3893         ast_channel_lock(transferer);
3894         transferer_name = ast_strdupa(ast_channel_name(transferer));
3895         transferer_bridgepeer = ast_strdupa(S_OR(pbx_builtin_getvar_helper(transferer, "BRIDGEPEER"), ""));
3896         ast_channel_unlock(transferer);
3897
3898         for (iter = ao2_iterator_init(channels, 0);
3899                         (chan = ao2_iterator_next(&iter));
3900                         ao2_cleanup(chan)) {
3901                 if (chan == transferer) {
3902                         pbx_builtin_setvar_helper(chan, "BLINDTRANSFER", transferer_bridgepeer);
3903                 } else {
3904                         pbx_builtin_setvar_helper(chan, "BLINDTRANSFER", transferer_name);
3905                 }
3906         }
3907
3908         ao2_iterator_destroy(&iter);
3909 }
3910
3911 static struct ast_bridge *acquire_bridge(struct ast_channel *chan)
3912 {
3913         struct ast_bridge *bridge;
3914
3915         ast_channel_lock(chan);
3916         bridge = ast_channel_get_bridge(chan);
3917         ast_channel_unlock(chan);
3918
3919         if (bridge
3920                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
3921                 ao2_ref(bridge, -1);
3922                 bridge = NULL;
3923         }
3924
3925         return bridge;
3926 }
3927
3928 static void publish_blind_transfer(int is_external, enum ast_transfer_result result,
3929                 struct ast_channel *transferer, struct ast_bridge *bridge,
3930                 const char *context, const char *exten)
3931 {
3932         struct ast_bridge_channel_pair pair;
3933         pair.channel = transferer;
3934         pair.bridge = bridge;
3935         ast_bridge_publish_blind_transfer(is_external, result, &pair, context, exten);
3936 }
3937
3938 enum ast_transfer_result ast_bridge_transfer_blind(int is_external,
3939                 struct ast_channel *transferer, const char *exten, const char *context,
3940                 transfer_channel_cb new_channel_cb, void *user_data)
3941 {
3942         RAII_VAR(struct ast_bridge *, bridge, NULL, ao2_cleanup);
3943         RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
3944         RAII_VAR(struct ao2_container *, channels, NULL, ao2_cleanup);
3945         RAII_VAR(struct ast_channel *, transferee, NULL, ast_channel_cleanup);
3946         int do_bridge_transfer;
3947         int transfer_prohibited;
3948         enum ast_transfer_result transfer_result;
3949
3950         bridge = acquire_bridge(transferer);
3951         if (!bridge) {
3952                 transfer_result = AST_BRIDGE_TRANSFER_INVALID;
3953                 goto publish;
3954         }
3955         ast_channel_lock(transferer);
3956         bridge_channel = ast_channel_get_bridge_channel(transferer);
3957         ast_channel_unlock(transferer);
3958         if (!bridge_channel) {
3959                 transfer_result = AST_BRIDGE_TRANSFER_INVALID;
3960                 goto publish;
3961         }
3962
3963         /* Take off hold if they are on hold. */
3964         ast_bridge_channel_write_unhold(bridge_channel);
3965
3966         transfer_result = try_parking(transferer, context, exten);
3967         if (transfer_result == AST_BRIDGE_TRANSFER_SUCCESS) {
3968                 goto publish;
3969         }
3970
3971         {
3972                 SCOPED_LOCK(lock, bridge, ast_bridge_lock, ast_bridge_unlock);
3973
3974                 channels = ast_bridge_peers_nolock(bridge);
3975                 if (!channels) {
3976