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