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