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