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