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