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