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