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