bridge.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 2007 - 2009, Digium, Inc.
00005  *
00006  * Joshua Colp <jcolp@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Bridging API
00022  *
00023  * \author Joshua Colp <jcolp@digium.com>
00024  */
00025 
00026 /*** MODULEINFO
00027    <support_level>core</support_level>
00028  ***/
00029 
00030 /*** DOCUMENTATION
00031    <manager name="BridgeTechnologyList" language="en_US">
00032       <synopsis>
00033          List available bridging technologies and their statuses.
00034       </synopsis>
00035       <syntax>
00036          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00037       </syntax>
00038       <description>
00039          <para>Returns detailed information about the available bridging technologies.</para>
00040       </description>
00041    </manager>
00042    <manager name="BridgeTechnologySuspend" language="en_US">
00043       <synopsis>
00044          Suspend a bridging technology.
00045       </synopsis>
00046       <syntax>
00047          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00048          <parameter name="BridgeTechnology" required="true">
00049             <para>The name of the bridging technology to suspend.</para>
00050          </parameter>
00051       </syntax>
00052       <description>
00053          <para>Marks a bridging technology as suspended, which prevents subsequently created bridges from using it.</para>
00054       </description>
00055    </manager>
00056    <manager name="BridgeTechnologyUnsuspend" language="en_US">
00057       <synopsis>
00058          Unsuspend a bridging technology.
00059       </synopsis>
00060       <syntax>
00061          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00062          <parameter name="BridgeTechnology" required="true">
00063             <para>The name of the bridging technology to unsuspend.</para>
00064          </parameter>
00065       </syntax>
00066       <description>
00067          <para>Clears a previously suspended bridging technology, which allows subsequently created bridges to use it.</para>
00068       </description>
00069    </manager>
00070 ***/
00071 
00072 #include "asterisk.h"
00073 
00074 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 434430 $")
00075 
00076 #include "asterisk/logger.h"
00077 #include "asterisk/channel.h"
00078 #include "asterisk/options.h"
00079 #include "asterisk/utils.h"
00080 #include "asterisk/lock.h"
00081 #include "asterisk/linkedlists.h"
00082 #include "asterisk/bridge.h"
00083 #include "asterisk/bridge_internal.h"
00084 #include "asterisk/bridge_channel_internal.h"
00085 #include "asterisk/bridge_features.h"
00086 #include "asterisk/bridge_basic.h"
00087 #include "asterisk/bridge_technology.h"
00088 #include "asterisk/bridge_channel.h"
00089 #include "asterisk/bridge_after.h"
00090 #include "asterisk/stasis_bridges.h"
00091 #include "asterisk/stasis_channels.h"
00092 #include "asterisk/stasis_cache_pattern.h"
00093 #include "asterisk/app.h"
00094 #include "asterisk/file.h"
00095 #include "asterisk/module.h"
00096 #include "asterisk/astobj2.h"
00097 #include "asterisk/pbx.h"
00098 #include "asterisk/test.h"
00099 #include "asterisk/_private.h"
00100 #include "asterisk/heap.h"
00101 #include "asterisk/say.h"
00102 #include "asterisk/timing.h"
00103 #include "asterisk/stringfields.h"
00104 #include "asterisk/musiconhold.h"
00105 #include "asterisk/features.h"
00106 #include "asterisk/cli.h"
00107 #include "asterisk/parking.h"
00108 #include "asterisk/core_local.h"
00109 #include "asterisk/core_unreal.h"
00110 #include "asterisk/causes.h"
00111 
00112 /*! All bridges container. */
00113 static struct ao2_container *bridges;
00114 
00115 static AST_RWLIST_HEAD_STATIC(bridge_technologies, ast_bridge_technology);
00116 
00117 static unsigned int optimization_id;
00118 
00119 /* Initial starting point for the bridge array of channels */
00120 #define BRIDGE_ARRAY_START 128
00121 
00122 /* Grow rate of bridge array of channels */
00123 #define BRIDGE_ARRAY_GROW 32
00124 
00125 /* Variable name - stores peer information about the most recent blind transfer */
00126 #define BLINDTRANSFER "BLINDTRANSFER"
00127 
00128 /* Variable name - stores peer information about the most recent attended transfer */
00129 #define ATTENDEDTRANSFER "ATTENDEDTRANSFER"
00130 
00131 static void cleanup_video_mode(struct ast_bridge *bridge);
00132 
00133 /*! Default DTMF keys for built in features */
00134 static char builtin_features_dtmf[AST_BRIDGE_BUILTIN_END][MAXIMUM_DTMF_FEATURE_STRING];
00135 
00136 /*! Function handlers for the built in features */
00137 static ast_bridge_hook_callback builtin_features_handlers[AST_BRIDGE_BUILTIN_END];
00138 
00139 /*! Function handlers for built in interval features */
00140 static ast_bridge_builtin_set_limits_fn builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_END];
00141 
00142 /*! Bridge manager service request */
00143 struct bridge_manager_request {
00144    /*! List of bridge service requests. */
00145    AST_LIST_ENTRY(bridge_manager_request) node;
00146    /*! Refed bridge requesting service. */
00147    struct ast_bridge *bridge;
00148 };
00149 
00150 struct bridge_manager_controller {
00151    /*! Condition, used to wake up the bridge manager thread. */
00152    ast_cond_t cond;
00153    /*! Queue of bridge service requests. */
00154    AST_LIST_HEAD_NOLOCK(, bridge_manager_request) service_requests;
00155    /*! Manager thread */
00156    pthread_t thread;
00157    /*! TRUE if the manager needs to stop. */
00158    unsigned int stop:1;
00159 };
00160 
00161 /*! Bridge manager controller. */
00162 static struct bridge_manager_controller *bridge_manager;
00163 
00164 /*!
00165  * \internal
00166  * \brief Request service for a bridge from the bridge manager.
00167  * \since 12.0.0
00168  *
00169  * \param bridge Requesting service.
00170  *
00171  * \return Nothing
00172  */
00173 static void bridge_manager_service_req(struct ast_bridge *bridge)
00174 {
00175    struct bridge_manager_request *request;
00176 
00177    ao2_lock(bridge_manager);
00178    if (bridge_manager->stop) {
00179       ao2_unlock(bridge_manager);
00180       return;
00181    }
00182 
00183    /* Create the service request. */
00184    request = ast_calloc(1, sizeof(*request));
00185    if (!request) {
00186       /* Well. This isn't good. */
00187       ao2_unlock(bridge_manager);
00188       return;
00189    }
00190    ao2_ref(bridge, +1);
00191    request->bridge = bridge;
00192 
00193    /* Put request into the queue and wake the bridge manager. */
00194    AST_LIST_INSERT_TAIL(&bridge_manager->service_requests, request, node);
00195    ast_cond_signal(&bridge_manager->cond);
00196    ao2_unlock(bridge_manager);
00197 }
00198 
00199 int __ast_bridge_technology_register(struct ast_bridge_technology *technology, struct ast_module *module)
00200 {
00201    struct ast_bridge_technology *current;
00202 
00203    /* Perform a sanity check to make sure the bridge technology conforms to our needed requirements */
00204    if (ast_strlen_zero(technology->name)
00205       || !technology->capabilities
00206       || !technology->write) {
00207       ast_log(LOG_WARNING, "Bridge technology %s failed registration sanity check.\n",
00208          technology->name);
00209       return -1;
00210    }
00211 
00212    AST_RWLIST_WRLOCK(&bridge_technologies);
00213 
00214    /* Look for duplicate bridge technology already using this name, or already registered */
00215    AST_RWLIST_TRAVERSE(&bridge_technologies, current, entry) {
00216       if ((!strcasecmp(current->name, technology->name)) || (current == technology)) {
00217          ast_log(LOG_WARNING, "A bridge technology of %s already claims to exist in our world.\n",
00218             technology->name);
00219          AST_RWLIST_UNLOCK(&bridge_technologies);
00220          return -1;
00221       }
00222    }
00223 
00224    /* Copy module pointer so reference counting can keep the module from unloading */
00225    technology->mod = module;
00226 
00227    /* Insert our new bridge technology into the list and print out a pretty message */
00228    AST_RWLIST_INSERT_TAIL(&bridge_technologies, technology, entry);
00229 
00230    AST_RWLIST_UNLOCK(&bridge_technologies);
00231 
00232    ast_verb(2, "Registered bridge technology %s\n", technology->name);
00233 
00234    return 0;
00235 }
00236 
00237 int ast_bridge_technology_unregister(struct ast_bridge_technology *technology)
00238 {
00239    struct ast_bridge_technology *current;
00240 
00241    AST_RWLIST_WRLOCK(&bridge_technologies);
00242 
00243    /* Ensure the bridge technology is registered before removing it */
00244    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&bridge_technologies, current, entry) {
00245       if (current == technology) {
00246          AST_RWLIST_REMOVE_CURRENT(entry);
00247          ast_verb(2, "Unregistered bridge technology %s\n", technology->name);
00248          break;
00249       }
00250    }
00251    AST_RWLIST_TRAVERSE_SAFE_END;
00252 
00253    AST_RWLIST_UNLOCK(&bridge_technologies);
00254 
00255    return current ? 0 : -1;
00256 }
00257 
00258 /*!
00259  * \internal
00260  * \brief Put an action onto the specified bridge. Don't dup the action frame.
00261  * \since 12.0.0
00262  *
00263  * \param bridge What to queue the action on.
00264  * \param action What to do.
00265  *
00266  * \return Nothing
00267  */
00268 static void bridge_queue_action_nodup(struct ast_bridge *bridge, struct ast_frame *action)
00269 {
00270    ast_debug(1, "Bridge %s: queueing action type:%u sub:%d\n",
00271       bridge->uniqueid, action->frametype, action->subclass.integer);
00272 
00273    ast_bridge_lock(bridge);
00274    AST_LIST_INSERT_TAIL(&bridge->action_queue, action, frame_list);
00275    ast_bridge_unlock(bridge);
00276    bridge_manager_service_req(bridge);
00277 }
00278 
00279 int ast_bridge_queue_action(struct ast_bridge *bridge, struct ast_frame *action)
00280 {
00281    struct ast_frame *dup;
00282 
00283    dup = ast_frdup(action);
00284    if (!dup) {
00285       return -1;
00286    }
00287    bridge_queue_action_nodup(bridge, dup);
00288    return 0;
00289 }
00290 
00291 void bridge_dissolve(struct ast_bridge *bridge, int cause)
00292 {
00293    struct ast_bridge_channel *bridge_channel;
00294    struct ast_frame action = {
00295       .frametype = AST_FRAME_BRIDGE_ACTION,
00296       .subclass.integer = BRIDGE_CHANNEL_ACTION_DEFERRED_DISSOLVING,
00297    };
00298 
00299    if (bridge->dissolved) {
00300       return;
00301    }
00302    bridge->dissolved = 1;
00303 
00304    if (cause <= 0) {
00305       cause = AST_CAUSE_NORMAL_CLEARING;
00306    }
00307    bridge->cause = cause;
00308 
00309    ast_debug(1, "Bridge %s: dissolving bridge with cause %d(%s)\n",
00310       bridge->uniqueid, cause, ast_cause2str(cause));
00311 
00312    AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
00313       ast_bridge_channel_leave_bridge(bridge_channel,
00314          BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, cause);
00315    }
00316 
00317    /* Must defer dissolving bridge because it is already locked. */
00318    ast_bridge_queue_action(bridge, &action);
00319 }
00320 
00321 /*!
00322  * \internal
00323  * \brief Check if a bridge should dissolve because of a stolen channel and do it.
00324  * \since 12.0.0
00325  *
00326  * \param bridge Bridge to check.
00327  * \param bridge_channel Stolen channel causing the check.  It is not in the bridge to check and may be in another bridge.
00328  *
00329  * \note On entry, bridge and bridge_channel->bridge are already locked.
00330  *
00331  * \return Nothing
00332  */
00333 static void bridge_dissolve_check_stolen(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
00334 {
00335    if (bridge->dissolved) {
00336       return;
00337    }
00338 
00339    if (bridge_channel->features->usable
00340       && ast_test_flag(&bridge_channel->features->feature_flags,
00341          AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP)) {
00342       /* The stolen channel controlled the bridge it was stolen from. */
00343       bridge_dissolve(bridge, 0);
00344       return;
00345    }
00346    if (bridge->num_channels < 2
00347       && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)) {
00348       /*
00349        * The stolen channel has not left enough channels to keep the
00350        * bridge alive.  Assume the stolen channel hung up.
00351        */
00352       bridge_dissolve(bridge, 0);
00353       return;
00354    }
00355 }
00356 
00357 /*!
00358  * \internal
00359  * \brief Update connected line information after a bridge has been reconfigured.
00360  *
00361  * \param bridge The bridge itself.
00362  *
00363  * \return Nothing
00364  */
00365 static void bridge_reconfigured_connected_line_update(struct ast_bridge *bridge)
00366 {
00367    struct ast_party_connected_line connected;
00368    struct ast_bridge_channel *bridge_channel = AST_LIST_FIRST(&bridge->channels), *peer;
00369    unsigned char data[1024];
00370    size_t datalen;
00371 
00372    if (!bridge_channel ||
00373       !(bridge->technology->capabilities & (AST_BRIDGE_CAPABILITY_1TO1MIX | AST_BRIDGE_CAPABILITY_NATIVE)) ||
00374       !(peer = ast_bridge_channel_peer(bridge_channel)) ||
00375       ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_ZOMBIE) ||
00376       ast_test_flag(ast_channel_flags(peer->chan), AST_FLAG_ZOMBIE) ||
00377       ast_check_hangup_locked(bridge_channel->chan) ||
00378       ast_check_hangup_locked(peer->chan)) {
00379       return;
00380    }
00381 
00382    ast_party_connected_line_init(&connected);
00383 
00384    ast_channel_lock(bridge_channel->chan);
00385    ast_connected_line_copy_from_caller(&connected, ast_channel_caller(bridge_channel->chan));
00386    ast_channel_unlock(bridge_channel->chan);
00387 
00388    if ((datalen = ast_connected_line_build_data(data, sizeof(data), &connected, NULL)) != (size_t) -1) {
00389       ast_bridge_channel_queue_control_data(peer, AST_CONTROL_CONNECTED_LINE, data, datalen);
00390    }
00391 
00392    ast_channel_lock(peer->chan);
00393    ast_connected_line_copy_from_caller(&connected, ast_channel_caller(peer->chan));
00394    ast_channel_unlock(peer->chan);
00395 
00396    if ((datalen = ast_connected_line_build_data(data, sizeof(data), &connected, NULL)) != (size_t) -1) {
00397       ast_bridge_channel_queue_control_data(bridge_channel, AST_CONTROL_CONNECTED_LINE, data, datalen);
00398    }
00399 
00400    ast_party_connected_line_free(&connected);
00401 }
00402 
00403 /*!
00404  * \internal
00405  * \brief Complete joining a channel to the bridge.
00406  * \since 12.0.0
00407  *
00408  * \param bridge What to operate upon.
00409  * \param bridge_channel What is joining the bridge technology.
00410  *
00411  * \note On entry, bridge is already locked.
00412  *
00413  * \return Nothing
00414  */
00415 static void bridge_channel_complete_join(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
00416 {
00417    /* Tell the bridge technology we are joining so they set us up */
00418    ast_debug(1, "Bridge %s: %p(%s) is joining %s technology\n",
00419       bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
00420       bridge->technology->name);
00421    if (bridge->technology->join
00422       && bridge->technology->join(bridge, bridge_channel)) {
00423       ast_debug(1, "Bridge %s: %p(%s) failed to join %s technology\n",
00424          bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
00425          bridge->technology->name);
00426       bridge_channel->just_joined = 1;
00427       return;
00428    }
00429 
00430    bridge_channel->just_joined = 0;
00431 }
00432 
00433 /*!
00434  * \internal
00435  * \brief Complete joining new channels to the bridge.
00436  * \since 12.0.0
00437  *
00438  * \param bridge Check for new channels on this bridge.
00439  *
00440  * \note On entry, bridge is already locked.
00441  *
00442  * \return Nothing
00443  */
00444 static void bridge_complete_join(struct ast_bridge *bridge)
00445 {
00446    struct ast_bridge_channel *bridge_channel;
00447 
00448    if (bridge->dissolved) {
00449       /*
00450        * No sense in completing the join on channels for a dissolved
00451        * bridge.  They are just going to be removed soon anyway.
00452        * However, we do have reason to abort here because the bridge
00453        * technology may not be able to handle the number of channels
00454        * still in the bridge.
00455        */
00456       return;
00457    }
00458 
00459    AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
00460       if (!bridge_channel->just_joined) {
00461          continue;
00462       }
00463       bridge_channel_complete_join(bridge, bridge_channel);
00464    }
00465 }
00466 
00467 /*! \brief Helper function used to find the "best" bridge technology given specified capabilities */
00468 static struct ast_bridge_technology *find_best_technology(uint32_t capabilities, struct ast_bridge *bridge)
00469 {
00470    struct ast_bridge_technology *current;
00471    struct ast_bridge_technology *best = NULL;
00472 
00473    AST_RWLIST_RDLOCK(&bridge_technologies);
00474    AST_RWLIST_TRAVERSE(&bridge_technologies, current, entry) {
00475       if (current->suspended) {
00476          ast_debug(1, "Bridge technology %s is suspended. Skipping.\n",
00477             current->name);
00478          continue;
00479       }
00480       if (!(current->capabilities & capabilities)) {
00481          ast_debug(1, "Bridge technology %s does not have any capabilities we want.\n",
00482             current->name);
00483          continue;
00484       }
00485       if (best && current->preference <= best->preference) {
00486          ast_debug(1, "Bridge technology %s has less preference than %s (%u <= %u). Skipping.\n",
00487             current->name, best->name, current->preference, best->preference);
00488          continue;
00489       }
00490       if (current->compatible && !current->compatible(bridge)) {
00491          ast_debug(1, "Bridge technology %s is not compatible with properties of existing bridge.\n",
00492             current->name);
00493          continue;
00494       }
00495       best = current;
00496    }
00497 
00498    if (best) {
00499       /* Increment it's module reference count if present so it does not get unloaded while in use */
00500       ast_module_ref(best->mod);
00501       ast_debug(1, "Chose bridge technology %s\n", best->name);
00502    }
00503 
00504    AST_RWLIST_UNLOCK(&bridge_technologies);
00505 
00506    return best;
00507 }
00508 
00509 struct tech_deferred_destroy {
00510    struct ast_bridge_technology *tech;
00511    void *tech_pvt;
00512 };
00513 
00514 /*!
00515  * \internal
00516  * \brief Deferred destruction of bridge tech private structure.
00517  * \since 12.0.0
00518  *
00519  * \param bridge What to execute the action on.
00520  * \param action Deferred bridge tech destruction.
00521  *
00522  * \note On entry, bridge must not be locked.
00523  *
00524  * \return Nothing
00525  */
00526 static void bridge_tech_deferred_destroy(struct ast_bridge *bridge, struct ast_frame *action)
00527 {
00528    struct tech_deferred_destroy *deferred = action->data.ptr;
00529    struct ast_bridge dummy_bridge = {
00530       .technology = deferred->tech,
00531       .tech_pvt = deferred->tech_pvt,
00532       .creator = bridge->creator,
00533       .name = bridge->name,
00534       .uniqueid = bridge->uniqueid,
00535       };
00536 
00537    ast_debug(1, "Bridge %s: calling %s technology destructor (deferred, dummy)\n",
00538       dummy_bridge.uniqueid, dummy_bridge.technology->name);
00539    dummy_bridge.technology->destroy(&dummy_bridge);
00540    ast_module_unref(dummy_bridge.technology->mod);
00541 }
00542 
00543 /*!
00544  * \internal
00545  * \brief Handle bridge action frame.
00546  * \since 12.0.0
00547  *
00548  * \param bridge What to execute the action on.
00549  * \param action What to do.
00550  *
00551  * \note On entry, bridge is already locked.
00552  * \note Can be called by the bridge destructor.
00553  *
00554  * \return Nothing
00555  */
00556 static void bridge_action_bridge(struct ast_bridge *bridge, struct ast_frame *action)
00557 {
00558 #if 0 /* In case we need to know when the destructor is calling us. */
00559    int in_destructor = !ao2_ref(bridge, 0);
00560 #endif
00561 
00562    switch (action->subclass.integer) {
00563    case BRIDGE_CHANNEL_ACTION_DEFERRED_TECH_DESTROY:
00564       ast_bridge_unlock(bridge);
00565       bridge_tech_deferred_destroy(bridge, action);
00566       ast_bridge_lock(bridge);
00567       break;
00568    case BRIDGE_CHANNEL_ACTION_DEFERRED_DISSOLVING:
00569       ast_bridge_unlock(bridge);
00570       bridge->v_table->dissolving(bridge);
00571       ast_bridge_lock(bridge);
00572       break;
00573    default:
00574       /* Unexpected deferred action type.  Should never happen. */
00575       ast_assert(0);
00576       break;
00577    }
00578 }
00579 
00580 /*!
00581  * \internal
00582  * \brief Do any pending bridge actions.
00583  * \since 12.0.0
00584  *
00585  * \param bridge What to do actions on.
00586  *
00587  * \note On entry, bridge is already locked.
00588  * \note Can be called by the bridge destructor.
00589  *
00590  * \return Nothing
00591  */
00592 static void bridge_handle_actions(struct ast_bridge *bridge)
00593 {
00594    struct ast_frame *action;
00595 
00596    while ((action = AST_LIST_REMOVE_HEAD(&bridge->action_queue, frame_list))) {
00597       switch (action->frametype) {
00598       case AST_FRAME_BRIDGE_ACTION:
00599          bridge_action_bridge(bridge, action);
00600          break;
00601       default:
00602          /* Unexpected deferred frame type.  Should never happen. */
00603          ast_assert(0);
00604          break;
00605       }
00606       ast_frfree(action);
00607    }
00608 }
00609 
00610 static struct stasis_message *create_bridge_snapshot_message(struct ast_bridge *bridge)
00611 {
00612    RAII_VAR(struct ast_bridge_snapshot *, snapshot, NULL, ao2_cleanup);
00613 
00614    if (!ast_bridge_snapshot_type()) {
00615       return NULL;
00616    }
00617 
00618    ast_bridge_lock(bridge);
00619    snapshot = ast_bridge_snapshot_create(bridge);
00620    ast_bridge_unlock(bridge);
00621 
00622    if (!snapshot) {
00623       return NULL;
00624    }
00625 
00626    return stasis_message_create(ast_bridge_snapshot_type(), snapshot);
00627 }
00628 
00629 static void destroy_bridge(void *obj)
00630 {
00631    struct ast_bridge *bridge = obj;
00632 
00633    ast_debug(1, "Bridge %s: actually destroying %s bridge, nobody wants it anymore\n",
00634       bridge->uniqueid, bridge->v_table->name);
00635 
00636    if (bridge->construction_completed) {
00637       RAII_VAR(struct stasis_message *, clear_msg, NULL, ao2_cleanup);
00638 
00639       clear_msg = create_bridge_snapshot_message(bridge);
00640       if (clear_msg) {
00641          RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
00642 
00643          msg = stasis_cache_clear_create(clear_msg);
00644          if (msg) {
00645             stasis_publish(ast_bridge_topic(bridge), msg);
00646          }
00647       }
00648    }
00649 
00650    /* Do any pending actions in the context of destruction. */
00651    ast_bridge_lock(bridge);
00652    bridge_handle_actions(bridge);
00653    ast_bridge_unlock(bridge);
00654 
00655    /* There should not be any channels left in the bridge. */
00656    ast_assert(AST_LIST_EMPTY(&bridge->channels));
00657 
00658    ast_debug(1, "Bridge %s: calling %s bridge destructor\n",
00659       bridge->uniqueid, bridge->v_table->name);
00660    bridge->v_table->destroy(bridge);
00661 
00662    /* Pass off the bridge to the technology to destroy if needed */
00663    if (bridge->technology) {
00664       ast_debug(1, "Bridge %s: calling %s technology stop\n",
00665          bridge->uniqueid, bridge->technology->name);
00666       if (bridge->technology->stop) {
00667          ast_bridge_lock(bridge);
00668          bridge->technology->stop(bridge);
00669          ast_bridge_unlock(bridge);
00670       }
00671       ast_debug(1, "Bridge %s: calling %s technology destructor\n",
00672          bridge->uniqueid, bridge->technology->name);
00673       if (bridge->technology->destroy) {
00674          bridge->technology->destroy(bridge);
00675       }
00676       ast_module_unref(bridge->technology->mod);
00677       bridge->technology = NULL;
00678    }
00679 
00680    bridge->callid = 0;
00681 
00682    cleanup_video_mode(bridge);
00683 
00684    stasis_cp_single_unsubscribe(bridge->topics);
00685 
00686    ast_string_field_free_memory(bridge);
00687 }
00688 
00689 struct ast_bridge *bridge_register(struct ast_bridge *bridge)
00690 {
00691    if (bridge) {
00692       bridge->construction_completed = 1;
00693       ast_bridge_lock(bridge);
00694       ast_bridge_publish_state(bridge);
00695       ast_bridge_unlock(bridge);
00696       if (!ao2_link(bridges, bridge)) {
00697          ast_bridge_destroy(bridge, 0);
00698          bridge = NULL;
00699       }
00700    }
00701    return bridge;
00702 }
00703 
00704 struct ast_bridge *bridge_alloc(size_t size, const struct ast_bridge_methods *v_table)
00705 {
00706    struct ast_bridge *bridge;
00707 
00708    /* Check v_table that all methods are present. */
00709    if (!v_table
00710       || !v_table->name
00711       || !v_table->destroy
00712       || !v_table->dissolving
00713       || !v_table->push
00714       || !v_table->pull
00715       || !v_table->notify_masquerade
00716       || !v_table->get_merge_priority) {
00717       ast_log(LOG_ERROR, "Virtual method table for bridge class %s not complete.\n",
00718          v_table && v_table->name ? v_table->name : "<unknown>");
00719       ast_assert(0);
00720       return NULL;
00721    }
00722 
00723    bridge = ao2_alloc(size, destroy_bridge);
00724    if (!bridge) {
00725       return NULL;
00726    }
00727 
00728    if (ast_string_field_init(bridge, 80)) {
00729       ao2_cleanup(bridge);
00730       return NULL;
00731    }
00732 
00733    bridge->v_table = v_table;
00734 
00735    return bridge;
00736 }
00737 
00738 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)
00739 {
00740    char uuid_hold[AST_UUID_STR_LEN];
00741 
00742    if (!self) {
00743       return NULL;
00744    }
00745 
00746    if (!ast_strlen_zero(id)) {
00747       ast_string_field_set(self, uniqueid, id);
00748    } else {
00749       ast_uuid_generate_str(uuid_hold, AST_UUID_STR_LEN);
00750       ast_string_field_set(self, uniqueid, uuid_hold);
00751    }
00752    ast_string_field_set(self, creator, creator);
00753    if (!ast_strlen_zero(creator)) {
00754       ast_string_field_set(self, name, name);
00755    }
00756 
00757    ast_set_flag(&self->feature_flags, flags);
00758    self->allowed_capabilities = capabilities;
00759 
00760    if (bridge_topics_init(self) != 0) {
00761       ast_log(LOG_WARNING, "Bridge %s: Could not initialize topics\n",
00762          self->uniqueid);
00763       ao2_ref(self, -1);
00764       return NULL;
00765    }
00766 
00767    /* Use our helper function to find the "best" bridge technology. */
00768    self->technology = find_best_technology(capabilities, self);
00769    if (!self->technology) {
00770       ast_log(LOG_WARNING, "Bridge %s: Could not create class %s.  No technology to support it.\n",
00771          self->uniqueid, self->v_table->name);
00772       ao2_ref(self, -1);
00773       return NULL;
00774    }
00775 
00776    /* Pass off the bridge to the technology to manipulate if needed */
00777    ast_debug(1, "Bridge %s: calling %s technology constructor\n",
00778       self->uniqueid, self->technology->name);
00779    if (self->technology->create && self->technology->create(self)) {
00780       ast_log(LOG_WARNING, "Bridge %s: failed to setup bridge technology %s\n",
00781          self->uniqueid, self->technology->name);
00782       ao2_ref(self, -1);
00783       return NULL;
00784    }
00785    ast_debug(1, "Bridge %s: calling %s technology start\n",
00786       self->uniqueid, self->technology->name);
00787    if (self->technology->start && self->technology->start(self)) {
00788       ast_log(LOG_WARNING, "Bridge %s: failed to start bridge technology %s\n",
00789          self->uniqueid, self->technology->name);
00790       ao2_ref(self, -1);
00791       return NULL;
00792    }
00793 
00794    if (!ast_bridge_topic(self)) {
00795       ao2_ref(self, -1);
00796       return NULL;
00797    }
00798 
00799    return self;
00800 }
00801 
00802 /*!
00803  * \internal
00804  * \brief ast_bridge base class destructor.
00805  * \since 12.0.0
00806  *
00807  * \param self Bridge to operate upon.
00808  *
00809  * \note Stub because of nothing to do.
00810  *
00811  * \return Nothing
00812  */
00813 static void bridge_base_destroy(struct ast_bridge *self)
00814 {
00815 }
00816 
00817 /*!
00818  * \internal
00819  * \brief The bridge is being dissolved.
00820  * \since 12.0.0
00821  *
00822  * \param self Bridge to operate upon.
00823  *
00824  * \return Nothing
00825  */
00826 static void bridge_base_dissolving(struct ast_bridge *self)
00827 {
00828    ao2_unlink(bridges, self);
00829 }
00830 
00831 /*!
00832  * \internal
00833  * \brief ast_bridge base push method.
00834  * \since 12.0.0
00835  *
00836  * \param self Bridge to operate upon.
00837  * \param bridge_channel Bridge channel to push.
00838  * \param swap Bridge channel to swap places with if not NULL.
00839  *
00840  * \note On entry, self is already locked.
00841  * \note Stub because of nothing to do.
00842  *
00843  * \retval 0 on success
00844  * \retval -1 on failure
00845  */
00846 static int bridge_base_push(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
00847 {
00848    return 0;
00849 }
00850 
00851 /*!
00852  * \internal
00853  * \brief ast_bridge base pull method.
00854  * \since 12.0.0
00855  *
00856  * \param self Bridge to operate upon.
00857  * \param bridge_channel Bridge channel to pull.
00858  *
00859  * \note On entry, self is already locked.
00860  *
00861  * \return Nothing
00862  */
00863 static void bridge_base_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
00864 {
00865    ast_bridge_features_remove(bridge_channel->features, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
00866 }
00867 
00868 /*!
00869  * \internal
00870  * \brief ast_bridge base notify_masquerade method.
00871  * \since 12.0.0
00872  *
00873  * \param self Bridge to operate upon.
00874  * \param bridge_channel Bridge channel that was masqueraded.
00875  *
00876  * \note On entry, self is already locked.
00877  *
00878  * \return Nothing
00879  */
00880 static void bridge_base_notify_masquerade(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
00881 {
00882    self->reconfigured = 1;
00883 }
00884 
00885 /*!
00886  * \internal
00887  * \brief Get the merge priority of this bridge.
00888  * \since 12.0.0
00889  *
00890  * \param self Bridge to operate upon.
00891  *
00892  * \note On entry, self is already locked.
00893  *
00894  * \return Merge priority
00895  */
00896 static int bridge_base_get_merge_priority(struct ast_bridge *self)
00897 {
00898    return 0;
00899 }
00900 
00901 /*!
00902  * \internal
00903  * \brief ast_bridge base push_peek method.
00904  * \since 13.2.0
00905  *
00906  * \param self Bridge to operate upon.
00907  * \param bridge_channel Bridge channel to push.
00908  * \param swap Bridge channel to swap places with if not NULL.
00909  *
00910  * \note On entry, self is already locked.
00911  * \note Stub because of nothing to do.
00912  *
00913  * \retval 0 on success
00914  * \retval -1 on failure
00915  */
00916 static int bridge_base_push_peek(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
00917 {
00918    return 0;
00919 }
00920 
00921 struct ast_bridge_methods ast_bridge_base_v_table = {
00922    .name = "base",
00923    .destroy = bridge_base_destroy,
00924    .dissolving = bridge_base_dissolving,
00925    .push = bridge_base_push,
00926    .pull = bridge_base_pull,
00927    .notify_masquerade = bridge_base_notify_masquerade,
00928    .get_merge_priority = bridge_base_get_merge_priority,
00929    .push_peek = bridge_base_push_peek,
00930 };
00931 
00932 struct ast_bridge *ast_bridge_base_new(uint32_t capabilities, unsigned int flags, const char *creator, const char *name, const char *id)
00933 {
00934    void *bridge;
00935 
00936    bridge = bridge_alloc(sizeof(struct ast_bridge), &ast_bridge_base_v_table);
00937    bridge = bridge_base_init(bridge, capabilities, flags, creator, name, id);
00938    bridge = bridge_register(bridge);
00939    return bridge;
00940 }
00941 
00942 int ast_bridge_destroy(struct ast_bridge *bridge, int cause)
00943 {
00944    ast_debug(1, "Bridge %s: telling all channels to leave the party\n", bridge->uniqueid);
00945    ast_bridge_lock(bridge);
00946    bridge_dissolve(bridge, cause);
00947    ast_bridge_unlock(bridge);
00948 
00949    ao2_ref(bridge, -1);
00950 
00951    return 0;
00952 }
00953 
00954 /*!
00955  * \internal
00956  * \brief Perform the smart bridge operation.
00957  * \since 12.0.0
00958  *
00959  * \param bridge Work on this bridge.
00960  *
00961  * \details
00962  * Basically see if a new bridge technology should be used instead
00963  * of the current one.
00964  *
00965  * \note On entry, bridge is already locked.
00966  *
00967  * \retval 0 on success.
00968  * \retval -1 on error.
00969  */
00970 static int smart_bridge_operation(struct ast_bridge *bridge)
00971 {
00972    uint32_t new_capabilities;
00973    struct ast_bridge_technology *new_technology;
00974    struct ast_bridge_technology *old_technology = bridge->technology;
00975    struct ast_bridge_channel *bridge_channel;
00976    struct ast_frame *deferred_action;
00977    struct ast_bridge dummy_bridge = {
00978       .technology = bridge->technology,
00979       .tech_pvt = bridge->tech_pvt,
00980       .creator = bridge->creator,
00981       .name = bridge->name,
00982       .uniqueid = bridge->uniqueid,
00983    };
00984 
00985    if (bridge->dissolved) {
00986       ast_debug(1, "Bridge %s is dissolved, not performing smart bridge operation.\n",
00987          bridge->uniqueid);
00988       return 0;
00989    }
00990 
00991    /* Determine new bridge technology capabilities needed. */
00992    if (2 < bridge->num_channels) {
00993       new_capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX;
00994       new_capabilities &= bridge->allowed_capabilities;
00995    } else {
00996       new_capabilities = AST_BRIDGE_CAPABILITY_NATIVE | AST_BRIDGE_CAPABILITY_1TO1MIX;
00997       new_capabilities &= bridge->allowed_capabilities;
00998       if (!new_capabilities
00999          && (bridge->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
01000          /* Allow switching between different multimix bridge technologies. */
01001          new_capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX;
01002       }
01003    }
01004 
01005    /* Find a bridge technology to satisfy the new capabilities. */
01006    new_technology = find_best_technology(new_capabilities, bridge);
01007    if (!new_technology) {
01008       int is_compatible = 0;
01009 
01010       if (old_technology->compatible) {
01011          is_compatible = old_technology->compatible(bridge);
01012       } else if (old_technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX) {
01013          is_compatible = 1;
01014       } else if (bridge->num_channels <= 2
01015          && (old_technology->capabilities & AST_BRIDGE_CAPABILITY_1TO1MIX)) {
01016          is_compatible = 1;
01017       }
01018 
01019       if (is_compatible) {
01020          ast_debug(1, "Bridge %s could not get a new technology, staying with old technology.\n",
01021             bridge->uniqueid);
01022          return 0;
01023       }
01024       ast_log(LOG_WARNING, "Bridge %s has no technology available to support it.\n",
01025          bridge->uniqueid);
01026       return -1;
01027    }
01028    if (new_technology == old_technology) {
01029       ast_debug(1, "Bridge %s is already using the new technology.\n",
01030          bridge->uniqueid);
01031       ast_module_unref(old_technology->mod);
01032       return 0;
01033    }
01034 
01035    if (old_technology->destroy) {
01036       struct tech_deferred_destroy deferred_tech_destroy = {
01037          .tech = dummy_bridge.technology,
01038          .tech_pvt = dummy_bridge.tech_pvt,
01039       };
01040       struct ast_frame action = {
01041          .frametype = AST_FRAME_BRIDGE_ACTION,
01042          .subclass.integer = BRIDGE_CHANNEL_ACTION_DEFERRED_TECH_DESTROY,
01043          .data.ptr = &deferred_tech_destroy,
01044          .datalen = sizeof(deferred_tech_destroy),
01045       };
01046 
01047       /*
01048        * We need to defer the bridge technology destroy callback
01049        * because we have the bridge locked.
01050        */
01051       deferred_action = ast_frdup(&action);
01052       if (!deferred_action) {
01053          ast_module_unref(new_technology->mod);
01054          return -1;
01055       }
01056    } else {
01057       deferred_action = NULL;
01058    }
01059 
01060    /*
01061     * We are now committed to changing the bridge technology.  We
01062     * must not release the bridge lock until we have installed the
01063     * new bridge technology.
01064     */
01065    ast_verb(4, "Bridge %s: switching from %s technology to %s\n",
01066       bridge->uniqueid, old_technology->name, new_technology->name);
01067 
01068    /*
01069     * Since we are soon going to pass this bridge to a new
01070     * technology we need to NULL out the tech_pvt pointer but
01071     * don't worry as it still exists in dummy_bridge, ditto for the
01072     * old technology.
01073     */
01074    bridge->tech_pvt = NULL;
01075    bridge->technology = new_technology;
01076 
01077    /* Setup the new bridge technology. */
01078    ast_debug(1, "Bridge %s: calling %s technology constructor\n",
01079       bridge->uniqueid, new_technology->name);
01080    if (new_technology->create && new_technology->create(bridge)) {
01081       ast_log(LOG_WARNING, "Bridge %s: failed to setup bridge technology %s\n",
01082          bridge->uniqueid, new_technology->name);
01083       bridge->tech_pvt = dummy_bridge.tech_pvt;
01084       bridge->technology = dummy_bridge.technology;
01085       ast_module_unref(new_technology->mod);
01086       return -1;
01087    }
01088 
01089    /* To ensure that things are sane for the old technology move the channels it
01090     * expects to the dummy bridge
01091     */
01092    AST_LIST_TRAVERSE_SAFE_BEGIN(&bridge->channels, bridge_channel, entry) {
01093       if (bridge_channel->just_joined) {
01094          continue;
01095       }
01096       ast_debug(1, "Bridge %s: moving %p(%s) to dummy bridge temporarily\n",
01097          bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
01098       AST_LIST_REMOVE_CURRENT(entry);
01099       AST_LIST_INSERT_TAIL(&dummy_bridge.channels, bridge_channel, entry);
01100       dummy_bridge.num_channels++;
01101       if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
01102          dummy_bridge.num_lonely++;
01103       }
01104       if (!bridge_channel->suspended) {
01105          dummy_bridge.num_active++;
01106       }
01107    }
01108    AST_LIST_TRAVERSE_SAFE_END;
01109 
01110    /* Take all the channels out of the old technology */
01111    AST_LIST_TRAVERSE_SAFE_BEGIN(&dummy_bridge.channels, bridge_channel, entry) {
01112       ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology (dummy)\n",
01113          dummy_bridge.uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
01114          old_technology->name);
01115       if (old_technology->leave) {
01116          old_technology->leave(&dummy_bridge, bridge_channel);
01117       }
01118       AST_LIST_REMOVE_CURRENT(entry);
01119       AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
01120       dummy_bridge.num_channels--;
01121       if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
01122          dummy_bridge.num_lonely--;
01123       }
01124       if (!bridge_channel->suspended) {
01125          dummy_bridge.num_active--;
01126       }
01127    }
01128    AST_LIST_TRAVERSE_SAFE_END;
01129 
01130    ast_debug(1, "Bridge %s: calling %s technology stop\n",
01131       dummy_bridge.uniqueid, old_technology->name);
01132    if (old_technology->stop) {
01133       old_technology->stop(&dummy_bridge);
01134    }
01135 
01136    /* Add any new channels or re-add existing channels to the bridge. */
01137    AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
01138       bridge_channel_complete_join(bridge, bridge_channel);
01139    }
01140 
01141    ast_debug(1, "Bridge %s: calling %s technology start\n",
01142       bridge->uniqueid, new_technology->name);
01143    if (new_technology->start && new_technology->start(bridge)) {
01144       ast_log(LOG_WARNING, "Bridge %s: failed to start bridge technology %s\n",
01145          bridge->uniqueid, new_technology->name);
01146    }
01147 
01148    /*
01149     * Now that all the channels have been moved over we need to get
01150     * rid of all the information the old technology may have left
01151     * around.
01152     */
01153    if (old_technology->destroy) {
01154       ast_debug(1, "Bridge %s: deferring %s technology destructor\n",
01155          dummy_bridge.uniqueid, old_technology->name);
01156       bridge_queue_action_nodup(bridge, deferred_action);
01157    } else {
01158       ast_debug(1, "Bridge %s: calling %s technology destructor\n",
01159          dummy_bridge.uniqueid, old_technology->name);
01160       ast_module_unref(old_technology->mod);
01161    }
01162 
01163    return 0;
01164 }
01165 
01166 /*!
01167  * \internal
01168  * \brief Bridge channel to check if a BRIDGE_PLAY_SOUND needs to be played.
01169  * \since 12.0.0
01170  *
01171  * \param bridge_channel What to check.
01172  *
01173  * \return Nothing
01174  */
01175 static void check_bridge_play_sound(struct ast_bridge_channel *bridge_channel)
01176 {
01177    const char *play_file;
01178 
01179    ast_channel_lock(bridge_channel->chan);
01180    play_file = pbx_builtin_getvar_helper(bridge_channel->chan, "BRIDGE_PLAY_SOUND");
01181    if (!ast_strlen_zero(play_file)) {
01182       play_file = ast_strdupa(play_file);
01183       pbx_builtin_setvar_helper(bridge_channel->chan, "BRIDGE_PLAY_SOUND", NULL);
01184    } else {
01185       play_file = NULL;
01186    }
01187    ast_channel_unlock(bridge_channel->chan);
01188 
01189    if (play_file) {
01190       ast_bridge_channel_queue_playfile(bridge_channel, NULL, play_file, NULL);
01191    }
01192 }
01193 
01194 /*!
01195  * \internal
01196  * \brief Check for any BRIDGE_PLAY_SOUND channel variables in the bridge.
01197  * \since 12.0.0
01198  *
01199  * \param bridge What to operate on.
01200  *
01201  * \note On entry, the bridge is already locked.
01202  *
01203  * \return Nothing
01204  */
01205 static void check_bridge_play_sounds(struct ast_bridge *bridge)
01206 {
01207    struct ast_bridge_channel *bridge_channel;
01208 
01209    AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
01210       check_bridge_play_sound(bridge_channel);
01211    }
01212 }
01213 
01214 static void update_bridge_vars_set(struct ast_channel *chan, const char *name, const char *pvtid)
01215 {
01216    ast_channel_stage_snapshot(chan);
01217    pbx_builtin_setvar_helper(chan, "BRIDGEPEER", name);
01218    pbx_builtin_setvar_helper(chan, "BRIDGEPVTCALLID", pvtid);
01219    ast_channel_stage_snapshot_done(chan);
01220 }
01221 
01222 /*!
01223  * \internal
01224  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a 2 party bridge.
01225  * \since 12.0.0
01226  *
01227  * \param c0 Party of the first part.
01228  * \param c1 Party of the second part.
01229  *
01230  * \note On entry, the bridge is already locked.
01231  * \note The bridge is expected to have exactly two parties.
01232  *
01233  * \return Nothing
01234  */
01235 static void set_bridge_peer_vars_2party(struct ast_channel *c0, struct ast_channel *c1)
01236 {
01237    const char *c0_name;
01238    const char *c1_name;
01239    const char *c0_pvtid = NULL;
01240    const char *c1_pvtid = NULL;
01241 #define UPDATE_BRIDGE_VARS_GET(chan, name, pvtid)                          \
01242    do {                                                        \
01243       name = ast_strdupa(ast_channel_name(chan));                          \
01244       if (ast_channel_tech(chan)->get_pvt_uniqueid) {                      \
01245          pvtid = ast_strdupa(ast_channel_tech(chan)->get_pvt_uniqueid(chan)); \
01246       }                                                        \
01247    } while (0)
01248 
01249    ast_channel_lock(c1);
01250    UPDATE_BRIDGE_VARS_GET(c1, c1_name, c1_pvtid);
01251    ast_channel_unlock(c1);
01252 
01253    ast_channel_lock(c0);
01254    update_bridge_vars_set(c0, c1_name, c1_pvtid);
01255    UPDATE_BRIDGE_VARS_GET(c0, c0_name, c0_pvtid);
01256    ast_channel_unlock(c0);
01257 
01258    ast_channel_lock(c1);
01259    update_bridge_vars_set(c1, c0_name, c0_pvtid);
01260    ast_channel_unlock(c1);
01261 }
01262 
01263 /*!
01264  * \internal
01265  * \brief Fill the BRIDGEPEER value buffer with a comma separated list of channel names.
01266  * \since 12.0.0
01267  *
01268  * \param buf Buffer to fill.  The caller must guarantee the buffer is large enough.
01269  * \param cur_idx Which index into names[] to skip.
01270  * \param names Channel names to put in the buffer.
01271  * \param num_names Number of names in the array.
01272  *
01273  * \return Nothing
01274  */
01275 static void fill_bridgepeer_buf(char *buf, unsigned int cur_idx, const char *names[], unsigned int num_names)
01276 {
01277    int need_separator = 0;
01278    unsigned int idx;
01279    const char *src;
01280    char *pos;
01281 
01282    pos = buf;
01283    for (idx = 0; idx < num_names; ++idx) {
01284       if (idx == cur_idx) {
01285          continue;
01286       }
01287 
01288       if (need_separator) {
01289          *pos++ = ',';
01290       }
01291       need_separator = 1;
01292 
01293       /* Copy name into buffer. */
01294       src = names[idx];
01295       while (*src) {
01296          *pos++ = *src++;
01297       }
01298    }
01299    *pos = '\0';
01300 }
01301 
01302 /*!
01303  * \internal
01304  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a multi-party bridge.
01305  * \since 12.0.0
01306  *
01307  * \param bridge What to operate on.
01308  *
01309  * \note On entry, the bridge is already locked.
01310  * \note The bridge is expected to have more than two parties.
01311  *
01312  * \return Nothing
01313  */
01314 static void set_bridge_peer_vars_multiparty(struct ast_bridge *bridge)
01315 {
01316 /*
01317  * Set a maximum number of channel names for the BRIDGEPEER
01318  * list.  The plus one is for the current channel which is not
01319  * put in the list.
01320  */
01321 #define MAX_BRIDGEPEER_CHANS  (10 + 1)
01322 
01323    unsigned int idx;
01324    unsigned int num_names;
01325    unsigned int len;
01326    const char **names;
01327    char *buf;
01328    struct ast_bridge_channel *bridge_channel;
01329 
01330    /* Get first MAX_BRIDGEPEER_CHANS channel names. */
01331    num_names = MIN(bridge->num_channels, MAX_BRIDGEPEER_CHANS);
01332    names = ast_alloca(num_names * sizeof(*names));
01333    idx = 0;
01334    AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
01335       if (num_names <= idx) {
01336          break;
01337       }
01338       ast_channel_lock(bridge_channel->chan);
01339       names[idx++] = ast_strdupa(ast_channel_name(bridge_channel->chan));
01340       ast_channel_unlock(bridge_channel->chan);
01341    }
01342 
01343    /* Determine maximum buf size needed. */
01344    len = num_names;
01345    for (idx = 0; idx < num_names; ++idx) {
01346       len += strlen(names[idx]);
01347    }
01348    buf = ast_alloca(len);
01349 
01350    /* Set the bridge channel variables. */
01351    idx = 0;
01352    buf[0] = '\0';
01353    AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
01354       if (idx < num_names) {
01355          fill_bridgepeer_buf(buf, idx, names, num_names);
01356       }
01357       ++idx;
01358 
01359       ast_channel_lock(bridge_channel->chan);
01360       update_bridge_vars_set(bridge_channel->chan, buf, NULL);
01361       ast_channel_unlock(bridge_channel->chan);
01362    }
01363 }
01364 
01365 /*!
01366  * \internal
01367  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a holding bridge.
01368  * \since 12.0.0
01369  *
01370  * \param bridge What to operate on.
01371  *
01372  * \note On entry, the bridge is already locked.
01373  *
01374  * \return Nothing
01375  */
01376 static void set_bridge_peer_vars_holding(struct ast_bridge *bridge)
01377 {
01378    struct ast_bridge_channel *bridge_channel;
01379 
01380    AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
01381       ast_channel_lock(bridge_channel->chan);
01382       update_bridge_vars_set(bridge_channel->chan, NULL, NULL);
01383       ast_channel_unlock(bridge_channel->chan);
01384    }
01385 }
01386 
01387 /*!
01388  * \internal
01389  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in the bridge.
01390  * \since 12.0.0
01391  *
01392  * \param bridge What to operate on.
01393  *
01394  * \note On entry, the bridge is already locked.
01395  *
01396  * \return Nothing
01397  */
01398 static void set_bridge_peer_vars(struct ast_bridge *bridge)
01399 {
01400    if (bridge->technology->capabilities & AST_BRIDGE_CAPABILITY_HOLDING) {
01401       set_bridge_peer_vars_holding(bridge);
01402       return;
01403    }
01404    if (bridge->num_channels < 2) {
01405       return;
01406    }
01407    if (bridge->num_channels == 2) {
01408       set_bridge_peer_vars_2party(AST_LIST_FIRST(&bridge->channels)->chan,
01409          AST_LIST_LAST(&bridge->channels)->chan);
01410    } else {
01411       set_bridge_peer_vars_multiparty(bridge);
01412    }
01413 }
01414 
01415 void bridge_reconfigured(struct ast_bridge *bridge, unsigned int colp_update)
01416 {
01417    if (!bridge->reconfigured) {
01418       return;
01419    }
01420    bridge->reconfigured = 0;
01421    if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_SMART)
01422       && smart_bridge_operation(bridge)) {
01423       /* Smart bridge failed. */
01424       bridge_dissolve(bridge, 0);
01425       return;
01426    }
01427    bridge_complete_join(bridge);
01428 
01429    if (bridge->dissolved) {
01430       return;
01431    }
01432    check_bridge_play_sounds(bridge);
01433    set_bridge_peer_vars(bridge);
01434    ast_bridge_publish_state(bridge);
01435 
01436    if (colp_update) {
01437       bridge_reconfigured_connected_line_update(bridge);
01438    }
01439 }
01440 
01441 struct ast_bridge_channel *bridge_find_channel(struct ast_bridge *bridge, struct ast_channel *chan)
01442 {
01443    struct ast_bridge_channel *bridge_channel;
01444 
01445    AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
01446       if (bridge_channel->chan == chan) {
01447          break;
01448       }
01449    }
01450 
01451    return bridge_channel;
01452 }
01453 
01454 void ast_bridge_notify_masquerade(struct ast_channel *chan)
01455 {
01456    struct ast_bridge_channel *bridge_channel;
01457    struct ast_bridge *bridge;
01458 
01459    /* Safely get the bridge_channel pointer for the chan. */
01460    ast_channel_lock(chan);
01461    bridge_channel = ast_channel_get_bridge_channel(chan);
01462    ast_channel_unlock(chan);
01463    if (!bridge_channel) {
01464       /* Not in a bridge */
01465       return;
01466    }
01467 
01468    ast_bridge_channel_lock_bridge(bridge_channel);
01469    bridge = bridge_channel->bridge;
01470    if (bridge_channel == bridge_find_channel(bridge, chan)) {
01471 /*
01472  * XXX ASTERISK-22366 this needs more work.  The channels need
01473  * to be made compatible again if the formats change. The
01474  * bridge_channel thread needs to monitor for this case.
01475  */
01476       /* The channel we want to notify is still in a bridge. */
01477       bridge->v_table->notify_masquerade(bridge, bridge_channel);
01478       bridge_reconfigured(bridge, 1);
01479    }
01480    ast_bridge_unlock(bridge);
01481    ao2_ref(bridge_channel, -1);
01482 }
01483 
01484 /*
01485  * XXX ASTERISK-21271 make ast_bridge_join() require features to be allocated just like ast_bridge_impart() and not expect the struct back.
01486  *
01487  * This change is really going to break ConfBridge.  All other
01488  * users are easily changed.  However, it is needed so the
01489  * bridging code can manipulate features on all channels
01490  * consistently no matter how they joined.
01491  *
01492  * Need to update the features parameter doxygen when this
01493  * change is made to be like ast_bridge_impart().
01494  */
01495 int ast_bridge_join(struct ast_bridge *bridge,
01496    struct ast_channel *chan,
01497    struct ast_channel *swap,
01498    struct ast_bridge_features *features,
01499    struct ast_bridge_tech_optimizations *tech_args,
01500    enum ast_bridge_join_flags flags)
01501 {
01502    struct ast_bridge_channel *bridge_channel;
01503    int res = 0;
01504 
01505    bridge_channel = bridge_channel_internal_alloc(bridge);
01506    if (flags & AST_BRIDGE_JOIN_PASS_REFERENCE) {
01507       ao2_ref(bridge, -1);
01508    }
01509    if (!bridge_channel) {
01510       ao2_t_cleanup(swap, "Error exit: bridge_channel alloc failed");
01511       res = -1;
01512       goto join_exit;
01513    }
01514 /* 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. */
01515    ast_assert(features != NULL);
01516    if (!features) {
01517       ao2_ref(bridge_channel, -1);
01518       ao2_t_cleanup(swap, "Error exit: features is NULL");
01519       res = -1;
01520       goto join_exit;
01521    }
01522    if (tech_args) {
01523       bridge_channel->tech_args = *tech_args;
01524    }
01525 
01526    ast_channel_lock(chan);
01527    if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE)) {
01528       res = -1;
01529    } else {
01530       ast_channel_internal_bridge_channel_set(chan, bridge_channel);
01531    }
01532    ast_channel_unlock(chan);
01533    bridge_channel->thread = pthread_self();
01534    bridge_channel->chan = chan;
01535    bridge_channel->swap = swap;
01536    bridge_channel->features = features;
01537    bridge_channel->inhibit_colp = !!(flags & AST_BRIDGE_JOIN_INHIBIT_JOIN_COLP);
01538 
01539    /* allow subclass to peek at upcoming push operation */
01540    if (bridge->v_table->push_peek && !res) {
01541       struct ast_bridge_channel *bcswap = NULL;
01542 
01543       ast_bridge_lock(bridge);
01544       if (bridge_channel->swap) {
01545          bcswap = bridge_find_channel(bridge, bridge_channel->swap);
01546       }
01547       res = bridge->v_table->push_peek(bridge, bridge_channel, bcswap);
01548       ast_bridge_unlock(bridge);
01549    }
01550 
01551    if (!res) {
01552       res = bridge_channel_internal_join(bridge_channel);
01553    }
01554 
01555    /* Cleanup all the data in the bridge channel after it leaves the bridge. */
01556    ast_channel_lock(chan);
01557    ast_channel_internal_bridge_channel_set(chan, NULL);
01558    ast_channel_unlock(chan);
01559    bridge_channel->chan = NULL;
01560    /* If bridge_channel->swap is not NULL then the join failed. */
01561    ao2_t_cleanup(bridge_channel->swap, "Bridge complete: join failed");
01562    bridge_channel->swap = NULL;
01563    bridge_channel->features = NULL;
01564 
01565    ao2_ref(bridge_channel, -1);
01566 
01567 join_exit:;
01568    ast_bridge_run_after_callback(chan);
01569    if (!(ast_channel_softhangup_internal_flag(chan) & AST_SOFTHANGUP_ASYNCGOTO)
01570       && !ast_bridge_setup_after_goto(chan)) {
01571       /* Claim the after bridge goto is an async goto destination. */
01572       ast_channel_lock(chan);
01573       ast_softhangup_nolock(chan, AST_SOFTHANGUP_ASYNCGOTO);
01574       ast_channel_unlock(chan);
01575    }
01576    return res;
01577 }
01578 
01579 /*! \brief Thread responsible for imparted bridged channels to be departed */
01580 static void *bridge_channel_depart_thread(void *data)
01581 {
01582    struct ast_bridge_channel *bridge_channel = data;
01583 
01584    if (bridge_channel->callid) {
01585       ast_callid_threadassoc_add(bridge_channel->callid);
01586    }
01587 
01588    bridge_channel_internal_join(bridge_channel);
01589 
01590    /*
01591     * cleanup
01592     *
01593     * If bridge_channel->swap is not NULL then the join failed.
01594     */
01595    ao2_t_cleanup(bridge_channel->swap, "Bridge complete: Departable impart join failed");
01596    bridge_channel->swap = NULL;
01597    ast_bridge_features_destroy(bridge_channel->features);
01598    bridge_channel->features = NULL;
01599 
01600    ast_bridge_discard_after_callback(bridge_channel->chan, AST_BRIDGE_AFTER_CB_REASON_DEPART);
01601    ast_bridge_discard_after_goto(bridge_channel->chan);
01602 
01603    return NULL;
01604 }
01605 
01606 /*! \brief Thread responsible for independent imparted bridged channels */
01607 static void *bridge_channel_ind_thread(void *data)
01608 {
01609    struct ast_bridge_channel *bridge_channel = data;
01610    struct ast_channel *chan;
01611 
01612    if (bridge_channel->callid) {
01613       ast_callid_threadassoc_add(bridge_channel->callid);
01614    }
01615 
01616    bridge_channel_internal_join(bridge_channel);
01617    chan = bridge_channel->chan;
01618 
01619    /* cleanup */
01620    ast_channel_lock(chan);
01621    ast_channel_internal_bridge_channel_set(chan, NULL);
01622    ast_channel_unlock(chan);
01623    bridge_channel->chan = NULL;
01624    /* If bridge_channel->swap is not NULL then the join failed. */
01625    ao2_t_cleanup(bridge_channel->swap, "Bridge complete: Independent impart join failed");
01626    bridge_channel->swap = NULL;
01627    ast_bridge_features_destroy(bridge_channel->features);
01628    bridge_channel->features = NULL;
01629 
01630    ao2_ref(bridge_channel, -1);
01631 
01632    ast_bridge_run_after_callback(chan);
01633    ast_bridge_run_after_goto(chan);
01634    return NULL;
01635 }
01636 
01637 int ast_bridge_impart(struct ast_bridge *bridge,
01638    struct ast_channel *chan,
01639    struct ast_channel *swap,
01640    struct ast_bridge_features *features,
01641    enum ast_bridge_impart_flags flags)
01642 {
01643    int res = 0;
01644    struct ast_bridge_channel *bridge_channel;
01645 
01646    /* Imparted channels cannot have a PBX. */
01647    if (ast_channel_pbx(chan)) {
01648       ast_log(AST_LOG_WARNING, "Channel %s has a PBX thread and cannot be imparted into bridge %s\n",
01649          ast_channel_name(chan), bridge->uniqueid);
01650       ast_bridge_features_destroy(features);
01651       return -1;
01652    }
01653 
01654    /* Supply an empty features structure if the caller did not. */
01655    if (!features) {
01656       features = ast_bridge_features_new();
01657       if (!features) {
01658          return -1;
01659       }
01660    }
01661 
01662    /* Try to allocate a structure for the bridge channel */
01663    bridge_channel = bridge_channel_internal_alloc(bridge);
01664    if (!bridge_channel) {
01665       ast_bridge_features_destroy(features);
01666       return -1;
01667    }
01668 
01669    ast_channel_lock(chan);
01670    if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE)) {
01671       ast_log(AST_LOG_NOTICE, "Channel %s is a zombie and cannot be imparted into bridge %s\n",
01672          ast_channel_name(chan), bridge->uniqueid);
01673       res = -1;
01674    } else {
01675       ast_channel_internal_bridge_channel_set(chan, bridge_channel);
01676    }
01677    ast_channel_unlock(chan);
01678    bridge_channel->chan = chan;
01679    bridge_channel->swap = ao2_t_bump(swap, "Setting up bridge impart");
01680    bridge_channel->features = features;
01681    bridge_channel->inhibit_colp = !!(flags & AST_BRIDGE_IMPART_INHIBIT_JOIN_COLP);
01682    bridge_channel->depart_wait =
01683       (flags & AST_BRIDGE_IMPART_CHAN_MASK) == AST_BRIDGE_IMPART_CHAN_DEPARTABLE;
01684    bridge_channel->callid = ast_read_threadstorage_callid();
01685 
01686    /* allow subclass to peek at swap channel before it can hangup */
01687    if (bridge->v_table->push_peek && !res) {
01688       struct ast_bridge_channel *bcswap = NULL;
01689 
01690       ast_bridge_lock(bridge);
01691       if (bridge_channel->swap) {
01692          bcswap = bridge_find_channel(bridge, bridge_channel->swap);
01693       }
01694       res = bridge->v_table->push_peek(bridge, bridge_channel, bcswap);
01695       ast_bridge_unlock(bridge);
01696    }
01697 
01698    /* Actually create the thread that will handle the channel */
01699    if (!res) {
01700       if ((flags & AST_BRIDGE_IMPART_CHAN_MASK) == AST_BRIDGE_IMPART_CHAN_INDEPENDENT) {
01701          res = ast_pthread_create_detached(&bridge_channel->thread, NULL,
01702             bridge_channel_ind_thread, bridge_channel);
01703       } else {
01704          res = ast_pthread_create(&bridge_channel->thread, NULL,
01705             bridge_channel_depart_thread, bridge_channel);
01706       }
01707    }
01708 
01709    if (res) {
01710       /* cleanup */
01711       ast_channel_lock(chan);
01712       ast_channel_internal_bridge_channel_set(chan, NULL);
01713       ast_channel_unlock(chan);
01714       bridge_channel->chan = NULL;
01715       ao2_t_cleanup(bridge_channel->swap, "Bridge complete: Impart failed");
01716       bridge_channel->swap = NULL;
01717       ast_bridge_features_destroy(bridge_channel->features);
01718       bridge_channel->features = NULL;
01719 
01720       ao2_ref(bridge_channel, -1);
01721       return -1;
01722    }
01723 
01724    return 0;
01725 }
01726 
01727 int ast_bridge_depart(struct ast_channel *chan)
01728 {
01729    struct ast_bridge_channel *bridge_channel;
01730    int departable;
01731 
01732    ast_channel_lock(chan);
01733    bridge_channel = ast_channel_internal_bridge_channel(chan);
01734    departable = bridge_channel && bridge_channel->depart_wait;
01735    ast_channel_unlock(chan);
01736    if (!departable) {
01737       ast_log(LOG_ERROR, "Channel %s cannot be departed.\n",
01738          ast_channel_name(chan));
01739       /*
01740        * Should never happen.  It likely means that
01741        * ast_bridge_depart() is called by two threads for the same
01742        * channel, the channel was never imparted to be departed, or it
01743        * has already been departed.
01744        */
01745       ast_assert(0);
01746       return -1;
01747    }
01748 
01749    /*
01750     * We are claiming the bridge_channel reference held by
01751     * bridge_channel_depart_thread().
01752     */
01753 
01754    ast_bridge_channel_leave_bridge(bridge_channel,
01755       BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
01756 
01757    /* Wait for the depart thread to die */
01758    ast_debug(1, "Waiting for %p(%s) bridge thread to die.\n",
01759       bridge_channel, ast_channel_name(bridge_channel->chan));
01760    pthread_join(bridge_channel->thread, NULL);
01761 
01762    ast_channel_lock(chan);
01763    ast_channel_internal_bridge_channel_set(chan, NULL);
01764    ast_channel_unlock(chan);
01765 
01766    /* We can get rid of the bridge_channel after the depart thread has died. */
01767    ao2_ref(bridge_channel, -1);
01768    return 0;
01769 }
01770 
01771 int ast_bridge_remove(struct ast_bridge *bridge, struct ast_channel *chan)
01772 {
01773    struct ast_bridge_channel *bridge_channel;
01774 
01775    ast_bridge_lock(bridge);
01776 
01777    /* Try to find the channel that we want to remove */
01778    if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
01779       ast_bridge_unlock(bridge);
01780       return -1;
01781    }
01782 
01783    ast_bridge_channel_leave_bridge(bridge_channel,
01784       BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
01785 
01786    ast_bridge_unlock(bridge);
01787 
01788    return 0;
01789 }
01790 
01791 static void kick_it(struct ast_bridge_channel *bridge_channel, const void *payload, size_t payload_size)
01792 {
01793    ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
01794 }
01795 
01796 int ast_bridge_kick(struct ast_bridge *bridge, struct ast_channel *chan)
01797 {
01798    struct ast_bridge_channel *bridge_channel;
01799    int res;
01800 
01801    ast_bridge_lock(bridge);
01802 
01803    /* Try to find the channel that we want to kick. */
01804    if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
01805       ast_bridge_unlock(bridge);
01806       return -1;
01807    }
01808 
01809    res = ast_bridge_channel_queue_callback(bridge_channel, 0, kick_it, NULL, 0);
01810 
01811    ast_bridge_unlock(bridge);
01812 
01813    return res;
01814 }
01815 
01816 /*!
01817  * \internal
01818  * \brief Point the bridge_channel to a new bridge.
01819  * \since 12.0.0
01820  *
01821  * \param bridge_channel What is to point to a new bridge.
01822  * \param new_bridge Where the bridge channel should point.
01823  *
01824  * \return Nothing
01825  */
01826 static void bridge_channel_change_bridge(struct ast_bridge_channel *bridge_channel, struct ast_bridge *new_bridge)
01827 {
01828    struct ast_bridge *old_bridge;
01829 
01830    ao2_ref(new_bridge, +1);
01831    ast_bridge_channel_lock(bridge_channel);
01832    ast_channel_lock(bridge_channel->chan);
01833    old_bridge = bridge_channel->bridge;
01834    bridge_channel->bridge = new_bridge;
01835    ast_channel_internal_bridge_set(bridge_channel->chan, new_bridge);
01836    ast_channel_unlock(bridge_channel->chan);
01837    ast_bridge_channel_unlock(bridge_channel);
01838    ao2_ref(old_bridge, -1);
01839 }
01840 
01841 static void bridge_channel_moving(struct ast_bridge_channel *bridge_channel, struct ast_bridge *src, struct ast_bridge *dst)
01842 {
01843    struct ast_bridge_features *features = bridge_channel->features;
01844    struct ast_bridge_hook *hook;
01845    struct ao2_iterator iter;
01846 
01847    /* Run any moving hooks. */
01848    iter = ao2_iterator_init(features->other_hooks, 0);
01849    for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
01850       int remove_me;
01851       ast_bridge_move_indicate_callback move_cb;
01852 
01853       if (hook->type != AST_BRIDGE_HOOK_TYPE_MOVE) {
01854          continue;
01855       }
01856       move_cb = (ast_bridge_move_indicate_callback) hook->callback;
01857       remove_me = move_cb(bridge_channel, hook->hook_pvt, src, dst);
01858       if (remove_me) {
01859          ast_debug(1, "Move detection hook %p is being removed from %p(%s)\n",
01860             hook, bridge_channel, ast_channel_name(bridge_channel->chan));
01861          ao2_unlink(features->other_hooks, hook);
01862       }
01863    }
01864    ao2_iterator_destroy(&iter);
01865 }
01866 
01867 void bridge_do_merge(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, struct ast_bridge_channel **kick_me, unsigned int num_kick,
01868    unsigned int optimized)
01869 {
01870    struct ast_bridge_channel *bridge_channel;
01871    unsigned int idx;
01872 
01873    ast_debug(1, "Merging bridge %s into bridge %s\n",
01874       src_bridge->uniqueid, dst_bridge->uniqueid);
01875 
01876    ast_bridge_publish_merge(dst_bridge, src_bridge);
01877 
01878    /*
01879     * Move channels from src_bridge over to dst_bridge.
01880     *
01881     * We must use AST_LIST_TRAVERSE_SAFE_BEGIN() because
01882     * bridge_channel_internal_pull() alters the list we are traversing.
01883     */
01884    AST_LIST_TRAVERSE_SAFE_BEGIN(&src_bridge->channels, bridge_channel, entry) {
01885       if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
01886          /*
01887           * The channel is already leaving let it leave normally because
01888           * pulling it may delete hooks that should run for this channel.
01889           */
01890          continue;
01891       }
01892       if (ast_test_flag(&bridge_channel->features->feature_flags,
01893          AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
01894          continue;
01895       }
01896 
01897       if (kick_me) {
01898          for (idx = 0; idx < num_kick; ++idx) {
01899             if (bridge_channel == kick_me[idx]) {
01900                ast_bridge_channel_leave_bridge(bridge_channel,
01901                   BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
01902                break;
01903             }
01904          }
01905       }
01906       bridge_channel_internal_pull(bridge_channel);
01907       if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
01908          /*
01909           * The channel died as a result of being pulled or it was
01910           * kicked.  Leave it pointing to the original bridge.
01911           */
01912          continue;
01913       }
01914 
01915       bridge_channel_moving(bridge_channel, bridge_channel->bridge, dst_bridge);
01916 
01917       /* Point to new bridge.*/
01918       bridge_channel_change_bridge(bridge_channel, dst_bridge);
01919 
01920       if (bridge_channel_internal_push(bridge_channel)) {
01921          ast_bridge_features_remove(bridge_channel->features,
01922             AST_BRIDGE_HOOK_REMOVE_ON_PULL);
01923          ast_bridge_channel_leave_bridge(bridge_channel,
01924             BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
01925       }
01926    }
01927    AST_LIST_TRAVERSE_SAFE_END;
01928 
01929    if (kick_me) {
01930       /*
01931        * Now we can kick any channels in the dst_bridge without
01932        * potentially dissolving the bridge.
01933        */
01934       for (idx = 0; idx < num_kick; ++idx) {
01935          bridge_channel = kick_me[idx];
01936          ast_bridge_channel_lock(bridge_channel);
01937          if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
01938             ast_bridge_channel_leave_bridge_nolock(bridge_channel,
01939                BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
01940             bridge_channel_internal_pull(bridge_channel);
01941          }
01942          ast_bridge_channel_unlock(bridge_channel);
01943       }
01944    }
01945 
01946    bridge_reconfigured(dst_bridge, !optimized);
01947    bridge_reconfigured(src_bridge, !optimized);
01948 
01949    ast_debug(1, "Merged bridge %s into bridge %s\n",
01950       src_bridge->uniqueid, dst_bridge->uniqueid);
01951 }
01952 
01953 struct merge_direction {
01954    /*! Destination merge bridge. */
01955    struct ast_bridge *dest;
01956    /*! Source merge bridge. */
01957    struct ast_bridge *src;
01958 };
01959 
01960 /*!
01961  * \internal
01962  * \brief Determine which bridge should merge into the other.
01963  * \since 12.0.0
01964  *
01965  * \param bridge1 A bridge for merging
01966  * \param bridge2 A bridge for merging
01967  *
01968  * \note The two bridges are assumed already locked.
01969  *
01970  * \return Which bridge merges into which or NULL bridges if cannot merge.
01971  */
01972 static struct merge_direction bridge_merge_determine_direction(struct ast_bridge *bridge1, struct ast_bridge *bridge2)
01973 {
01974    struct merge_direction merge = { NULL, NULL };
01975    int bridge1_priority;
01976    int bridge2_priority;
01977 
01978    if (!ast_test_flag(&bridge1->feature_flags,
01979          AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)
01980       && !ast_test_flag(&bridge2->feature_flags,
01981          AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
01982       /*
01983        * Can merge either way.  Merge to the higher priority merge
01984        * bridge.  Otherwise merge to the larger bridge.
01985        */
01986       bridge1_priority = bridge1->v_table->get_merge_priority(bridge1);
01987       bridge2_priority = bridge2->v_table->get_merge_priority(bridge2);
01988       if (bridge2_priority < bridge1_priority) {
01989          merge.dest = bridge1;
01990          merge.src = bridge2;
01991       } else if (bridge1_priority < bridge2_priority) {
01992          merge.dest = bridge2;
01993          merge.src = bridge1;
01994       } else {
01995          /* Merge to the larger bridge. */
01996          if (bridge2->num_channels <= bridge1->num_channels) {
01997             merge.dest = bridge1;
01998             merge.src = bridge2;
01999          } else {
02000             merge.dest = bridge2;
02001             merge.src = bridge1;
02002          }
02003       }
02004    } else if (!ast_test_flag(&bridge1->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
02005       && !ast_test_flag(&bridge2->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
02006       /* Can merge only one way. */
02007       merge.dest = bridge1;
02008       merge.src = bridge2;
02009    } else if (!ast_test_flag(&bridge2->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
02010       && !ast_test_flag(&bridge1->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
02011       /* Can merge only one way. */
02012       merge.dest = bridge2;
02013       merge.src = bridge1;
02014    }
02015 
02016    return merge;
02017 }
02018 
02019 /*!
02020  * \internal
02021  * \brief Merge two bridges together
02022  * \since 12.0.0
02023  *
02024  * \param dst_bridge Destination bridge of merge.
02025  * \param src_bridge Source bridge of merge.
02026  * \param merge_best_direction TRUE if don't care about which bridge merges into the other.
02027  * \param kick_me Array of channels to kick from the bridges.
02028  * \param num_kick Number of channels in the kick_me array.
02029  *
02030  * \note The dst_bridge and src_bridge are assumed already locked.
02031  *
02032  * \retval 0 on success
02033  * \retval -1 on failure
02034  */
02035 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)
02036 {
02037    struct merge_direction merge;
02038    struct ast_bridge_channel **kick_them = NULL;
02039 
02040    /* Sanity check. */
02041    ast_assert(dst_bridge && src_bridge && dst_bridge != src_bridge && (!num_kick || kick_me));
02042 
02043    if (dst_bridge->dissolved || src_bridge->dissolved) {
02044       ast_debug(1, "Can't merge bridges %s and %s, at least one bridge is dissolved.\n",
02045          src_bridge->uniqueid, dst_bridge->uniqueid);
02046       return -1;
02047    }
02048    if (ast_test_flag(&dst_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)
02049       || ast_test_flag(&src_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
02050       ast_debug(1, "Can't merge bridges %s and %s, masquerade only.\n",
02051          src_bridge->uniqueid, dst_bridge->uniqueid);
02052       return -1;
02053    }
02054    if (dst_bridge->inhibit_merge || src_bridge->inhibit_merge) {
02055       ast_debug(1, "Can't merge bridges %s and %s, merging temporarily inhibited.\n",
02056          src_bridge->uniqueid, dst_bridge->uniqueid);
02057       return -1;
02058    }
02059 
02060    if (merge_best_direction) {
02061       merge = bridge_merge_determine_direction(dst_bridge, src_bridge);
02062    } else {
02063       merge.dest = dst_bridge;
02064       merge.src = src_bridge;
02065    }
02066 
02067    if (!merge.dest
02068       || ast_test_flag(&merge.dest->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_TO)
02069       || ast_test_flag(&merge.src->feature_flags, AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM)) {
02070       ast_debug(1, "Can't merge bridges %s and %s, merging inhibited.\n",
02071          src_bridge->uniqueid, dst_bridge->uniqueid);
02072       return -1;
02073    }
02074    if (merge.src->num_channels < 2) {
02075       /*
02076        * For a two party bridge, a channel may be temporarily removed
02077        * from the source bridge or the initial bridge members have not
02078        * joined yet.
02079        */
02080       ast_debug(1, "Can't merge bridge %s into bridge %s, not enough channels in source bridge.\n",
02081          merge.src->uniqueid, merge.dest->uniqueid);
02082       return -1;
02083    }
02084    if (2 + num_kick < merge.dest->num_channels + merge.src->num_channels
02085       && !(merge.dest->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)
02086       && (!ast_test_flag(&merge.dest->feature_flags, AST_BRIDGE_FLAG_SMART)
02087          || !(merge.dest->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX))) {
02088       ast_debug(1, "Can't merge bridge %s into bridge %s, multimix is needed and it cannot be acquired.\n",
02089          merge.src->uniqueid, merge.dest->uniqueid);
02090       return -1;
02091    }
02092 
02093    if (num_kick) {
02094       unsigned int num_to_kick = 0;
02095       unsigned int idx;
02096 
02097       kick_them = ast_alloca(num_kick * sizeof(*kick_them));
02098       for (idx = 0; idx < num_kick; ++idx) {
02099          kick_them[num_to_kick] = bridge_find_channel(merge.src, kick_me[idx]);
02100          if (!kick_them[num_to_kick]) {
02101             kick_them[num_to_kick] = bridge_find_channel(merge.dest, kick_me[idx]);
02102          }
02103          if (kick_them[num_to_kick]) {
02104             ++num_to_kick;
02105          }
02106       }
02107 
02108       if (num_to_kick != num_kick) {
02109          ast_debug(1, "Can't merge bridge %s into bridge %s, at least one kicked channel is not in either bridge.\n",
02110             merge.src->uniqueid, merge.dest->uniqueid);
02111          return -1;
02112       }
02113    }
02114 
02115    bridge_do_merge(merge.dest, merge.src, kick_them, num_kick, 0);
02116    return 0;
02117 }
02118 
02119 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)
02120 {
02121    int res;
02122 
02123    /* Sanity check. */
02124    ast_assert(dst_bridge && src_bridge);
02125 
02126    ast_bridge_lock_both(dst_bridge, src_bridge);
02127    res = bridge_merge_locked(dst_bridge, src_bridge, merge_best_direction, kick_me, num_kick);
02128    ast_bridge_unlock(src_bridge);
02129    ast_bridge_unlock(dst_bridge);
02130    return res;
02131 }
02132 
02133 int bridge_do_move(struct ast_bridge *dst_bridge, struct ast_bridge_channel *bridge_channel, int attempt_recovery,
02134    unsigned int optimized)
02135 {
02136    struct ast_bridge *orig_bridge;
02137    int was_in_bridge;
02138    int res = 0;
02139 
02140    if (bridge_channel->swap) {
02141       ast_debug(1, "Moving %p(%s) into bridge %s swapping with %s\n",
02142          bridge_channel, ast_channel_name(bridge_channel->chan), dst_bridge->uniqueid,
02143          ast_channel_name(bridge_channel->swap));
02144    } else {
02145       ast_debug(1, "Moving %p(%s) into bridge %s\n",
02146          bridge_channel, ast_channel_name(bridge_channel->chan), dst_bridge->uniqueid);
02147    }
02148 
02149    orig_bridge = bridge_channel->bridge;
02150    was_in_bridge = bridge_channel->in_bridge;
02151 
02152    bridge_channel_internal_pull(bridge_channel);
02153    if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
02154       /*
02155        * The channel died as a result of being pulled.  Leave it
02156        * pointing to the original bridge.
02157        *
02158        * Clear out the swap channel pointer.  A ref is not held
02159        * by bridge_channel->swap at this point.
02160        */
02161       bridge_channel->swap = NULL;
02162       bridge_reconfigured(orig_bridge, 0);
02163       return -1;
02164    }
02165 
02166    /* Point to new bridge.*/
02167    ao2_ref(orig_bridge, +1);/* Keep a ref in case the push fails. */
02168    bridge_channel_change_bridge(bridge_channel, dst_bridge);
02169 
02170    bridge_channel_moving(bridge_channel, orig_bridge, dst_bridge);
02171 
02172    if (bridge_channel_internal_push(bridge_channel)) {
02173       /* Try to put the channel back into the original bridge. */
02174       ast_bridge_features_remove(bridge_channel->features,
02175          AST_BRIDGE_HOOK_REMOVE_ON_PULL);
02176       if (attempt_recovery && was_in_bridge) {
02177          /* Point back to original bridge. */
02178          bridge_channel_change_bridge(bridge_channel, orig_bridge);
02179 
02180          if (bridge_channel_internal_push(bridge_channel)) {
02181             ast_bridge_features_remove(bridge_channel->features,
02182                AST_BRIDGE_HOOK_REMOVE_ON_PULL);
02183             ast_bridge_channel_leave_bridge(bridge_channel,
02184                BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
02185             bridge_channel_settle_owed_events(orig_bridge, bridge_channel);
02186          }
02187       } else {
02188          ast_bridge_channel_leave_bridge(bridge_channel,
02189             BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
02190          bridge_channel_settle_owed_events(orig_bridge, bridge_channel);
02191       }
02192       res = -1;
02193    } else {
02194       bridge_channel_settle_owed_events(orig_bridge, bridge_channel);
02195    }
02196 
02197    bridge_reconfigured(dst_bridge, !optimized);
02198    bridge_reconfigured(orig_bridge, !optimized);
02199    ao2_ref(orig_bridge, -1);
02200    return res;
02201 }
02202 
02203 /*!
02204  * \internal
02205  * \brief Move a channel from one bridge to another.
02206  * \since 12.0.0
02207  *
02208  * \param dst_bridge Destination bridge of bridge channel move.
02209  * \param src_bridge Source bridge of bridge channel move.
02210  * \param chan Channel to move.
02211  * \param swap Channel to replace in dst_bridge.
02212  * \param attempt_recovery TRUE if failure attempts to push channel back into original bridge.
02213  *
02214  * \note The dst_bridge and src_bridge are assumed already locked.
02215  *
02216  * \retval 0 on success.
02217  * \retval -1 on failure.
02218  */
02219 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)
02220 {
02221    struct ast_bridge_channel *bridge_channel;
02222 
02223    if (dst_bridge->dissolved || src_bridge->dissolved) {
02224       ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, at least one bridge is dissolved.\n",
02225          ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
02226       return -1;
02227    }
02228    if (ast_test_flag(&dst_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)
02229       || ast_test_flag(&src_bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
02230       ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, masquerade only.\n",
02231          ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
02232       return -1;
02233    }
02234    if (dst_bridge->inhibit_merge || src_bridge->inhibit_merge) {
02235       ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, temporarily inhibited.\n",
02236          ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
02237       return -1;
02238    }
02239 
02240    bridge_channel = bridge_find_channel(src_bridge, chan);
02241    if (!bridge_channel) {
02242       ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel not in bridge.\n",
02243          ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
02244       return -1;
02245    }
02246    if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
02247       ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel leaving bridge.\n",
02248          ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
02249       return -1;
02250    }
02251    if (ast_test_flag(&bridge_channel->features->feature_flags,
02252       AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
02253       ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, channel immovable.\n",
02254          ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid);
02255       return -1;
02256    }
02257 
02258    if (swap) {
02259       struct ast_bridge_channel *bridge_channel_swap;
02260 
02261       bridge_channel_swap = bridge_find_channel(dst_bridge, swap);
02262       if (!bridge_channel_swap) {
02263          ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, swap channel %s not in bridge.\n",
02264             ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid,
02265             ast_channel_name(swap));
02266          return -1;
02267       }
02268       if (bridge_channel_swap->state != BRIDGE_CHANNEL_STATE_WAIT) {
02269          ast_debug(1, "Can't move channel %s from bridge %s into bridge %s, swap channel %s leaving bridge.\n",
02270             ast_channel_name(chan), src_bridge->uniqueid, dst_bridge->uniqueid,
02271             ast_channel_name(swap));
02272          return -1;
02273       }
02274    }
02275 
02276    bridge_channel->swap = swap;
02277    return bridge_do_move(dst_bridge, bridge_channel, attempt_recovery, 0);
02278 }
02279 
02280 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)
02281 {
02282    int res;
02283 
02284    ast_bridge_lock_both(dst_bridge, src_bridge);
02285    res = bridge_move_locked(dst_bridge, src_bridge, chan, swap, attempt_recovery);
02286    ast_bridge_unlock(src_bridge);
02287    ast_bridge_unlock(dst_bridge);
02288    return res;
02289 }
02290 
02291 int ast_bridge_add_channel(struct ast_bridge *bridge, struct ast_channel *chan,
02292    struct ast_bridge_features *features, int play_tone, const char *xfersound)
02293 {
02294    RAII_VAR(struct ast_bridge *, chan_bridge, NULL, ao2_cleanup);
02295    RAII_VAR(struct ast_channel *, yanked_chan, NULL, ao2_cleanup);
02296 
02297    ast_channel_lock(chan);
02298    chan_bridge = ast_channel_get_bridge(chan);
02299    ast_channel_unlock(chan);
02300 
02301    if (chan_bridge) {
02302       struct ast_bridge_channel *bridge_channel;
02303 
02304       ast_bridge_lock_both(bridge, chan_bridge);
02305       bridge_channel = bridge_find_channel(chan_bridge, chan);
02306 
02307       if (bridge_move_locked(bridge, chan_bridge, chan, NULL, 1)) {
02308          ast_bridge_unlock(chan_bridge);
02309          ast_bridge_unlock(bridge);
02310          return -1;
02311       }
02312 
02313       /*
02314        * bridge_move_locked() will implicitly ensure that
02315        * bridge_channel is not NULL.
02316        */
02317       ast_assert(bridge_channel != NULL);
02318 
02319       /*
02320        * Additional checks if the channel we just stole dissolves the
02321        * original bridge.
02322        */
02323       bridge_dissolve_check_stolen(chan_bridge, bridge_channel);
02324       ast_bridge_unlock(chan_bridge);
02325       ast_bridge_unlock(bridge);
02326 
02327       /* The channel was in a bridge so it is not getting any new features. */
02328       ast_bridge_features_destroy(features);
02329    } else {
02330       /* Slightly less easy case. We need to yank channel A from
02331        * where he currently is and impart him into our bridge.
02332        */
02333       yanked_chan = ast_channel_yank(chan);
02334       if (!yanked_chan) {
02335          ast_log(LOG_WARNING, "Could not gain control of channel %s\n", ast_channel_name(chan));
02336          return -1;
02337       }
02338       if (ast_channel_state(yanked_chan) != AST_STATE_UP) {
02339          ast_answer(yanked_chan);
02340       }
02341       ast_channel_ref(yanked_chan);
02342       if (ast_bridge_impart(bridge, yanked_chan, NULL, features,
02343          AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
02344          /* It is possible for us to yank a channel and have some other
02345           * thread start a PBX on the channl after we yanked it. In particular,
02346           * this can theoretically happen on the ;2 of a Local channel if we
02347           * yank it prior to the ;1 being answered. Make sure that it isn't
02348           * executing a PBX before hanging it up.
02349           */
02350          if (ast_channel_pbx(yanked_chan)) {
02351             ast_channel_unref(yanked_chan);
02352          } else {
02353             ast_hangup(yanked_chan);
02354          }
02355          return -1;
02356       }
02357    }
02358 
02359    if (play_tone && !ast_strlen_zero(xfersound)) {
02360       struct ast_channel *play_chan = yanked_chan ?: chan;
02361       RAII_VAR(struct ast_bridge_channel *, play_bridge_channel, NULL, ao2_cleanup);
02362 
02363       ast_channel_lock(play_chan);
02364       play_bridge_channel = ast_channel_get_bridge_channel(play_chan);
02365       ast_channel_unlock(play_chan);
02366 
02367       if (!play_bridge_channel) {
02368          ast_log(LOG_WARNING, "Unable to play tone for channel %s. No longer in a bridge.\n",
02369             ast_channel_name(play_chan));
02370       } else {
02371          ast_bridge_channel_queue_playfile(play_bridge_channel, NULL, xfersound, NULL);
02372       }
02373    }
02374    return 0;
02375 }
02376 
02377 static int bridge_allows_optimization(struct ast_bridge *bridge)
02378 {
02379    return !(bridge->inhibit_merge
02380       || bridge->dissolved
02381       || ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY));
02382 }
02383 
02384 /*!
02385  * \internal
02386  * \brief Lock the unreal channel stack for chan and prequalify it.
02387  * \since 12.0.0
02388  *
02389  * \param chan Unreal channel writing a frame into the channel driver.
02390  *
02391  * \note It is assumed that chan is already locked.
02392  *
02393  * \retval bridge on success with bridge and bridge_channel locked.
02394  * \retval NULL if cannot do optimization now.
02395  */
02396 static struct ast_bridge *optimize_lock_chan_stack(struct ast_channel *chan)
02397 {
02398    struct ast_bridge *bridge;
02399    struct ast_bridge_channel *bridge_channel;
02400 
02401    if (!AST_LIST_EMPTY(ast_channel_readq(chan))) {
02402       return NULL;
02403    }
02404    if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF)) {
02405       return NULL;
02406    }
02407    if (ast_channel_has_audio_frame_or_monitor(chan)) {
02408       /* Channel has an active monitor, audiohook, or framehook. */
02409       return NULL;
02410    }
02411    bridge_channel = ast_channel_internal_bridge_channel(chan);
02412    if (!bridge_channel || ast_bridge_channel_trylock(bridge_channel)) {
02413       return NULL;
02414    }
02415    bridge = bridge_channel->bridge;
02416    if (bridge_channel->activity != BRIDGE_CHANNEL_THREAD_SIMPLE
02417       || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
02418       || ast_bridge_trylock(bridge)) {
02419       ast_bridge_channel_unlock(bridge_channel);
02420       return NULL;
02421    }
02422    if (!bridge_channel_internal_allows_optimization(bridge_channel) ||
02423          !bridge_allows_optimization(bridge)) {
02424       ast_bridge_unlock(bridge);
02425       ast_bridge_channel_unlock(bridge_channel);
02426       return NULL;
02427    }
02428    return bridge;
02429 }
02430 
02431 /*!
02432  * \internal
02433  * \brief Lock the unreal channel stack for peer and prequalify it.
02434  * \since 12.0.0
02435  *
02436  * \param peer Other unreal channel in the pair.
02437  *
02438  * \retval bridge on success with bridge, bridge_channel, and peer locked.
02439  * \retval NULL if cannot do optimization now.
02440  */
02441 static struct ast_bridge *optimize_lock_peer_stack(struct ast_channel *peer)
02442 {
02443    struct ast_bridge *bridge;
02444    struct ast_bridge_channel *bridge_channel;
02445 
02446    if (ast_channel_trylock(peer)) {
02447       return NULL;
02448    }
02449    if (!AST_LIST_EMPTY(ast_channel_readq(peer))) {
02450       ast_channel_unlock(peer);
02451       return NULL;
02452    }
02453    if (ast_test_flag(ast_channel_flags(peer), AST_FLAG_EMULATE_DTMF)) {
02454       ast_channel_unlock(peer);
02455       return NULL;
02456    }
02457    if (ast_channel_has_audio_frame_or_monitor(peer)) {
02458       /* Peer has an active monitor, audiohook, or framehook. */
02459       ast_channel_unlock(peer);
02460       return NULL;
02461    }
02462    bridge_channel = ast_channel_internal_bridge_channel(peer);
02463    if (!bridge_channel || ast_bridge_channel_trylock(bridge_channel)) {
02464       ast_channel_unlock(peer);
02465       return NULL;
02466    }
02467    bridge = bridge_channel->bridge;
02468    if (bridge_channel->activity != BRIDGE_CHANNEL_THREAD_IDLE
02469       || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
02470       || ast_bridge_trylock(bridge)) {
02471       ast_bridge_channel_unlock(bridge_channel);
02472       ast_channel_unlock(peer);
02473       return NULL;
02474    }
02475    if (!bridge_allows_optimization(bridge) ||
02476          !bridge_channel_internal_allows_optimization(bridge_channel)) {
02477       ast_bridge_unlock(bridge);
02478       ast_bridge_channel_unlock(bridge_channel);
02479       ast_channel_unlock(peer);
02480       return NULL;
02481    }
02482    return bridge;
02483 }
02484 
02485 /*!
02486  * \internal
02487  * \brief Indicates allowability of a swap optimization
02488  */
02489 enum bridge_allow_swap {
02490    /*! Bridges cannot allow for a swap optimization to occur */
02491    SWAP_PROHIBITED,
02492    /*! Bridge swap optimization can occur into the chan_bridge */
02493    SWAP_TO_CHAN_BRIDGE,
02494    /*! Bridge swap optimization can occur into the peer_bridge */
02495    SWAP_TO_PEER_BRIDGE,
02496 };
02497 
02498 /*!
02499  * \internal
02500  * \brief Determine if two bridges allow for swap optimization to occur
02501  *
02502  * \param chan_bridge First bridge being tested
02503  * \param peer_bridge Second bridge being tested
02504  * \return Allowability of swap optimization
02505  */
02506 static enum bridge_allow_swap bridges_allow_swap_optimization(struct ast_bridge *chan_bridge,
02507       struct ast_bridge *peer_bridge)
02508 {
02509    int chan_priority;
02510    int peer_priority;
02511 
02512    if (!ast_test_flag(&chan_bridge->feature_flags,
02513          AST_BRIDGE_FLAG_SWAP_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM |
02514          AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
02515       && !ast_test_flag(&peer_bridge->feature_flags,
02516          AST_BRIDGE_FLAG_SWAP_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM |
02517          AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)) {
02518       /*
02519        * Can swap either way.  Swap to the higher priority merge
02520        * bridge.
02521        */
02522       chan_priority = chan_bridge->v_table->get_merge_priority(chan_bridge);
02523       peer_priority = peer_bridge->v_table->get_merge_priority(peer_bridge);
02524       if (chan_bridge->num_channels == 2
02525          && chan_priority <= peer_priority) {
02526          return SWAP_TO_PEER_BRIDGE;
02527       } else if (peer_bridge->num_channels == 2
02528          && peer_priority <= chan_priority) {
02529          return SWAP_TO_CHAN_BRIDGE;
02530       }
02531    } else if (chan_bridge->num_channels == 2
02532       && !ast_test_flag(&chan_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM | AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
02533       && !ast_test_flag(&peer_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_TO)) {
02534       /* Can swap optimize only one way. */
02535       return SWAP_TO_PEER_BRIDGE;
02536    } else if (peer_bridge->num_channels == 2
02537       && !ast_test_flag(&peer_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM | AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY)
02538       && !ast_test_flag(&chan_bridge->feature_flags, AST_BRIDGE_FLAG_SWAP_INHIBIT_TO)) {
02539       /* Can swap optimize only one way. */
02540       return SWAP_TO_CHAN_BRIDGE;
02541    }
02542 
02543    return SWAP_PROHIBITED;
02544 }
02545 
02546 /*!
02547  * \internal
02548  * \brief Check and attempt to swap optimize out the unreal channels.
02549  * \since 12.0.0
02550  *
02551  * \param chan_bridge
02552  * \param chan_bridge_channel
02553  * \param peer_bridge
02554  * \param peer_bridge_channel
02555  * \param pvt Unreal data containing callbacks to call if the optimization actually
02556  * happens
02557  *
02558  * \retval 1 if unreal channels failed to optimize out.
02559  * \retval 0 if unreal channels were not optimized out.
02560  * \retval -1 if unreal channels were optimized out.
02561  */
02562 static int try_swap_optimize_out(struct ast_bridge *chan_bridge,
02563    struct ast_bridge_channel *chan_bridge_channel, struct ast_bridge *peer_bridge,
02564    struct ast_bridge_channel *peer_bridge_channel,
02565    struct ast_unreal_pvt *pvt)
02566 {
02567    struct ast_bridge *dst_bridge;
02568    struct ast_bridge_channel *dst_bridge_channel;
02569    struct ast_bridge_channel *src_bridge_channel;
02570    struct ast_bridge_channel *other;
02571    int res = 1;
02572 
02573    switch (bridges_allow_swap_optimization(chan_bridge, peer_bridge)) {
02574    case SWAP_TO_CHAN_BRIDGE:
02575       dst_bridge = chan_bridge;
02576       dst_bridge_channel = chan_bridge_channel;
02577       src_bridge_channel = peer_bridge_channel;
02578       break;
02579    case SWAP_TO_PEER_BRIDGE:
02580       dst_bridge = peer_bridge;
02581       dst_bridge_channel = peer_bridge_channel;
02582       src_bridge_channel = chan_bridge_channel;
02583       break;
02584    case SWAP_PROHIBITED:
02585    default:
02586       return 0;
02587    }
02588 
02589    other = ast_bridge_channel_peer(src_bridge_channel);
02590    if (other && other->state == BRIDGE_CHANNEL_STATE_WAIT) {
02591       unsigned int id;
02592 
02593       if (ast_channel_trylock(other->chan)) {
02594          return 1;
02595       }
02596 
02597       id = ast_atomic_fetchadd_int((int *) &optimization_id, +1);
02598 
02599       ast_verb(4, "Move-swap optimizing %s <-- %s.\n",
02600          ast_channel_name(dst_bridge_channel->chan),
02601          ast_channel_name(other->chan));
02602 
02603       if (pvt && !ast_test_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN) && pvt->callbacks
02604             && pvt->callbacks->optimization_started) {
02605          pvt->callbacks->optimization_started(pvt, other->chan,
02606                dst_bridge_channel->chan == pvt->owner ? AST_UNREAL_OWNER : AST_UNREAL_CHAN,
02607                id);
02608          ast_set_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN);
02609       }
02610       other->swap = dst_bridge_channel->chan;
02611       if (!bridge_do_move(dst_bridge, other, 1, 1)) {
02612          ast_bridge_channel_leave_bridge(src_bridge_channel,
02613             BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
02614          res = -1;
02615       }
02616       if (pvt && pvt->callbacks && pvt->callbacks->optimization_finished) {
02617          pvt->callbacks->optimization_finished(pvt, res == 1, id);
02618       }
02619       ast_channel_unlock(other->chan);
02620    }
02621    return res;
02622 }
02623 
02624 /*!
02625  * \internal
02626  * \brief Indicates allowability of a merge optimization
02627  */
02628 enum bridge_allow_merge {
02629    /*! Bridge properties prohibit merge optimization */
02630    MERGE_PROHIBITED,
02631    /*! Merge optimization cannot occur because the source bridge has too few channels */
02632    MERGE_NOT_ENOUGH_CHANNELS,
02633    /*! Merge optimization cannot occur because multimix capability could not be requested */
02634    MERGE_NO_MULTIMIX,
02635    /*! Merge optimization allowed between bridges */
02636    MERGE_ALLOWED,
02637 };
02638 
02639 /*!
02640  * \internal
02641  * \brief Determines allowability of a merge optimization
02642  *
02643  * \note The merge output parameter is undefined if MERGE_PROHIBITED is returned. For success
02644  * and other failure returns, a merge direction was determined, and the parameter is safe to
02645  * access.
02646  *
02647  * \param chan_bridge First bridge being tested
02648  * \param peer_bridge Second bridge being tested
02649  * \param num_kick_channels The number of channels to remove from the bridges during merging
02650  * \param[out] merge Indicates the recommended direction for the bridge merge
02651  */
02652 static enum bridge_allow_merge bridges_allow_merge_optimization(struct ast_bridge *chan_bridge,
02653       struct ast_bridge *peer_bridge, int num_kick_channels, struct merge_direction *merge)
02654 {
02655    *merge = bridge_merge_determine_direction(chan_bridge, peer_bridge);
02656    if (!merge->dest) {
02657       return MERGE_PROHIBITED;
02658    }
02659    if (merge->src->num_channels < 2) {
02660       return MERGE_NOT_ENOUGH_CHANNELS;
02661    } else if ((2 + num_kick_channels) < merge->dest->num_channels + merge->src->num_channels
02662       && !(merge->dest->technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)
02663       && (!ast_test_flag(&merge->dest->feature_flags, AST_BRIDGE_FLAG_SMART)
02664          || !(merge->dest->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX))) {
02665       return MERGE_NO_MULTIMIX;
02666    }
02667 
02668    return MERGE_ALLOWED;
02669 }
02670 
02671 /*!
02672  * \internal
02673  * \brief Check and attempt to merge optimize out the unreal channels.
02674  * \since 12.0.0
02675  *
02676  * \param chan_bridge
02677  * \param chan_bridge_channel
02678  * \param peer_bridge
02679  * \param peer_bridge_channel
02680  * \param pvt Unreal data containing callbacks to call if the optimization actually
02681  * happens
02682  *
02683  * \retval 0 if unreal channels were not optimized out.
02684  * \retval -1 if unreal channels were optimized out.
02685  */
02686 static int try_merge_optimize_out(struct ast_bridge *chan_bridge,
02687    struct ast_bridge_channel *chan_bridge_channel, struct ast_bridge *peer_bridge,
02688    struct ast_bridge_channel *peer_bridge_channel,
02689    struct ast_unreal_pvt *pvt)
02690 {
02691    struct merge_direction merge;
02692    struct ast_bridge_channel *kick_me[] = {
02693       chan_bridge_channel,
02694       peer_bridge_channel,
02695    };
02696    unsigned int id;
02697 
02698    switch (bridges_allow_merge_optimization(chan_bridge, peer_bridge, ARRAY_LEN(kick_me), &merge)) {
02699    case MERGE_ALLOWED:
02700       break;
02701    case MERGE_PROHIBITED:
02702       return 0;
02703    case MERGE_NOT_ENOUGH_CHANNELS:
02704       ast_debug(4, "Can't optimize %s -- %s out, not enough channels in bridge %s.\n",
02705          ast_channel_name(chan_bridge_channel->chan),
02706          ast_channel_name(peer_bridge_channel->chan),
02707          merge.src->uniqueid);
02708       return 0;
02709    case MERGE_NO_MULTIMIX:
02710       ast_debug(4, "Can't optimize %s -- %s out, multimix is needed and it cannot be acquired.\n",
02711          ast_channel_name(chan_bridge_channel->chan),
02712          ast_channel_name(peer_bridge_channel->chan));
02713       return 0;
02714    }
02715 
02716    ast_verb(4, "Merge optimizing %s -- %s out.\n",
02717       ast_channel_name(chan_bridge_channel->chan),
02718       ast_channel_name(peer_bridge_channel->chan));
02719 
02720    id = ast_atomic_fetchadd_int((int *) &optimization_id, +1);
02721 
02722    if (pvt && !ast_test_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN) && pvt->callbacks
02723          && pvt->callbacks->optimization_started) {
02724       pvt->callbacks->optimization_started(pvt, NULL,
02725             merge.dest == ast_channel_internal_bridge(pvt->owner) ? AST_UNREAL_OWNER : AST_UNREAL_CHAN,
02726             id);
02727       ast_set_flag(pvt, AST_UNREAL_OPTIMIZE_BEGUN);
02728    }
02729    bridge_do_merge(merge.dest, merge.src, kick_me, ARRAY_LEN(kick_me), 1);
02730    if (pvt && pvt->callbacks && pvt->callbacks->optimization_finished) {
02731       pvt->callbacks->optimization_finished(pvt, 1, id);
02732    }
02733 
02734    return -1;
02735 }
02736 
02737 int ast_bridge_unreal_optimize_out(struct ast_channel *chan, struct ast_channel *peer, struct ast_unreal_pvt *pvt)
02738 {
02739    struct ast_bridge *chan_bridge;
02740    struct ast_bridge *peer_bridge;
02741    struct ast_bridge_channel *chan_bridge_channel;
02742    struct ast_bridge_channel *peer_bridge_channel;
02743    int res = 0;
02744 
02745    chan_bridge = optimize_lock_chan_stack(chan);
02746    if (!chan_bridge) {
02747       return res;
02748    }
02749    chan_bridge_channel = ast_channel_internal_bridge_channel(chan);
02750 
02751    peer_bridge = optimize_lock_peer_stack(peer);
02752    if (peer_bridge) {
02753       peer_bridge_channel = ast_channel_internal_bridge_channel(peer);
02754 
02755       res = try_swap_optimize_out(chan_bridge, chan_bridge_channel,
02756          peer_bridge, peer_bridge_channel, pvt);
02757       if (!res) {
02758          res = try_merge_optimize_out(chan_bridge, chan_bridge_channel,
02759             peer_bridge, peer_bridge_channel, pvt);
02760       } else if (0 < res) {
02761          res = 0;
02762       }
02763 
02764       /* Release peer locks. */
02765       ast_bridge_unlock(peer_bridge);
02766       ast_bridge_channel_unlock(peer_bridge_channel);
02767       ast_channel_unlock(peer);
02768    }
02769 
02770    /* Release chan locks. */
02771    ast_bridge_unlock(chan_bridge);
02772    ast_bridge_channel_unlock(chan_bridge_channel);
02773 
02774    return res;
02775 }
02776 
02777 enum ast_bridge_optimization ast_bridges_allow_optimization(struct ast_bridge *chan_bridge,
02778       struct ast_bridge *peer_bridge)
02779 {
02780    struct merge_direction merge;
02781 
02782    if (!bridge_allows_optimization(chan_bridge) || !bridge_allows_optimization(peer_bridge)) {
02783       return AST_BRIDGE_OPTIMIZE_PROHIBITED;
02784    }
02785 
02786    switch (bridges_allow_swap_optimization(chan_bridge, peer_bridge)) {
02787    case SWAP_TO_CHAN_BRIDGE:
02788       return AST_BRIDGE_OPTIMIZE_SWAP_TO_CHAN_BRIDGE;
02789    case SWAP_TO_PEER_BRIDGE:
02790       return AST_BRIDGE_OPTIMIZE_SWAP_TO_PEER_BRIDGE;
02791    case SWAP_PROHIBITED:
02792    default:
02793       break;
02794    }
02795 
02796    /* Two channels will be kicked from the bridges, the unreal;1 and unreal;2 channels */
02797    if (bridges_allow_merge_optimization(chan_bridge, peer_bridge, 2, &merge) != MERGE_ALLOWED) {
02798       return AST_BRIDGE_OPTIMIZE_PROHIBITED;
02799    }
02800 
02801    if (merge.dest == chan_bridge) {
02802       return AST_BRIDGE_OPTIMIZE_MERGE_TO_CHAN_BRIDGE;
02803    } else {
02804       return AST_BRIDGE_OPTIMIZE_MERGE_TO_PEER_BRIDGE;
02805    }
02806 }
02807 
02808 /*!
02809  * \internal
02810  * \brief Adjust the bridge merge inhibit request count.
02811  * \since 12.0.0
02812  *
02813  * \param bridge What to operate on.
02814  * \param request Inhibit request increment.
02815  *     (Positive to add requests.  Negative to remove requests.)
02816  *
02817  * \note This function assumes bridge is locked.
02818  *
02819  * \return Nothing
02820  */
02821 void bridge_merge_inhibit_nolock(struct ast_bridge *bridge, int request)
02822 {
02823    int new_request;
02824 
02825    new_request = bridge->inhibit_merge + request;
02826    ast_assert(0 <= new_request);
02827    bridge->inhibit_merge = new_request;
02828 }
02829 
02830 void ast_bridge_merge_inhibit(struct ast_bridge *bridge, int request)
02831 {
02832    ast_bridge_lock(bridge);
02833    bridge_merge_inhibit_nolock(bridge, request);
02834    ast_bridge_unlock(bridge);
02835 }
02836 
02837 int ast_bridge_suspend(struct ast_bridge *bridge, struct ast_channel *chan)
02838 {
02839    struct ast_bridge_channel *bridge_channel;
02840 /* XXX ASTERISK-21271 the case of a disolved bridge while channel is suspended is not handled. */
02841 /* XXX ASTERISK-21271 suspend/unsuspend needs to be rethought. The caller must block until it has successfully suspended the channel for temporary control. */
02842 /* 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. */
02843 
02844    ast_bridge_lock(bridge);
02845 
02846    if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
02847       ast_bridge_unlock(bridge);
02848       return -1;
02849    }
02850 
02851    bridge_channel_internal_suspend_nolock(bridge_channel);
02852 
02853    ast_bridge_unlock(bridge);
02854 
02855    return 0;
02856 }
02857 
02858 int ast_bridge_unsuspend(struct ast_bridge *bridge, struct ast_channel *chan)
02859 {
02860    struct ast_bridge_channel *bridge_channel;
02861 /* XXX ASTERISK-21271 the case of a disolved bridge while channel is suspended is not handled. */
02862 
02863    ast_bridge_lock(bridge);
02864 
02865    if (!(bridge_channel = bridge_find_channel(bridge, chan))) {
02866       ast_bridge_unlock(bridge);
02867       return -1;
02868    }
02869 
02870    bridge_channel_internal_unsuspend_nolock(bridge_channel);
02871 
02872    ast_bridge_unlock(bridge);
02873 
02874    return 0;
02875 }
02876 
02877 void ast_bridge_technology_suspend(struct ast_bridge_technology *technology)
02878 {
02879    technology->suspended = 1;
02880 }
02881 
02882 void ast_bridge_technology_unsuspend(struct ast_bridge_technology *technology)
02883 {
02884    /*
02885     * XXX We may want the act of unsuspending a bridge technology
02886     * to prod all existing bridges to see if they should start
02887     * using it.
02888     */
02889    technology->suspended = 0;
02890 }
02891 
02892 int ast_bridge_features_register(enum ast_bridge_builtin_feature feature, ast_bridge_hook_callback callback, const char *dtmf)
02893 {
02894    if (ARRAY_LEN(builtin_features_handlers) <= feature
02895       || builtin_features_handlers[feature]) {
02896       return -1;
02897    }
02898 
02899    if (!ast_strlen_zero(dtmf)) {
02900       ast_copy_string(builtin_features_dtmf[feature], dtmf, sizeof(builtin_features_dtmf[feature]));
02901    }
02902 
02903    builtin_features_handlers[feature] = callback;
02904 
02905    return 0;
02906 }
02907 
02908 int ast_bridge_features_unregister(enum ast_bridge_builtin_feature feature)
02909 {
02910    if (ARRAY_LEN(builtin_features_handlers) <= feature
02911       || !builtin_features_handlers[feature]) {
02912       return -1;
02913    }
02914 
02915    builtin_features_handlers[feature] = NULL;
02916 
02917    return 0;
02918 }
02919 
02920 int ast_bridge_features_do(enum ast_bridge_builtin_feature feature, struct ast_bridge_channel *bridge_channel, void *hook_pvt)
02921 {
02922    ast_bridge_hook_callback callback;
02923 
02924    if (ARRAY_LEN(builtin_features_handlers) <= feature) {
02925       return -1;
02926    }
02927 
02928    callback = builtin_features_handlers[feature];
02929    if (!callback) {
02930       return -1;
02931    }
02932    callback(bridge_channel, hook_pvt);
02933 
02934    return 0;
02935 }
02936 
02937 int ast_bridge_interval_register(enum ast_bridge_builtin_interval interval, ast_bridge_builtin_set_limits_fn callback)
02938 {
02939    if (ARRAY_LEN(builtin_interval_handlers) <= interval
02940       || builtin_interval_handlers[interval]) {
02941       return -1;
02942    }
02943 
02944    builtin_interval_handlers[interval] = callback;
02945 
02946    return 0;
02947 }
02948 
02949 int ast_bridge_interval_unregister(enum ast_bridge_builtin_interval interval)
02950 {
02951    if (ARRAY_LEN(builtin_interval_handlers) <= interval
02952       || !builtin_interval_handlers[interval]) {
02953       return -1;
02954    }
02955 
02956    builtin_interval_handlers[interval] = NULL;
02957 
02958    return 0;
02959 
02960 }
02961 
02962 /*!
02963  * \internal
02964  * \brief Bridge hook destructor.
02965  * \since 12.0.0
02966  *
02967  * \param vhook Object to destroy.
02968  *
02969  * \return Nothing
02970  */
02971 static void bridge_hook_destroy(void *vhook)
02972 {
02973    struct ast_bridge_hook *hook = vhook;
02974 
02975    if (hook->destructor) {
02976       hook->destructor(hook->hook_pvt);
02977    }
02978 }
02979 
02980 /*!
02981  * \internal
02982  * \brief Allocate and setup a generic bridge hook.
02983  * \since 12.0.0
02984  *
02985  * \param size How big an object to allocate.
02986  * \param callback Function to execute upon activation
02987  * \param hook_pvt Unique data
02988  * \param destructor Optional destructor callback for hook_pvt data
02989  * \param remove_flags Dictates what situations the hook should be removed.
02990  *
02991  * \retval hook on success.
02992  * \retval NULL on error.
02993  */
02994 static struct ast_bridge_hook *bridge_hook_generic(size_t size,
02995    ast_bridge_hook_callback callback,
02996    void *hook_pvt,
02997    ast_bridge_hook_pvt_destructor destructor,
02998    enum ast_bridge_hook_remove_flags remove_flags)
02999 {
03000    struct ast_bridge_hook *hook;
03001 
03002    /* Allocate new hook and setup it's basic variables */
03003    hook = ao2_alloc_options(size, bridge_hook_destroy, AO2_ALLOC_OPT_LOCK_NOLOCK);
03004    if (hook) {
03005       hook->callback = callback;
03006       hook->destructor = destructor;
03007       hook->hook_pvt = hook_pvt;
03008       ast_set_flag(&hook->remove_flags, remove_flags);
03009    }
03010 
03011    return hook;
03012 }
03013 
03014 int ast_bridge_dtmf_hook(struct ast_bridge_features *features,
03015    const char *dtmf,
03016    ast_bridge_hook_callback callback,
03017    void *hook_pvt,
03018    ast_bridge_hook_pvt_destructor destructor,
03019    enum ast_bridge_hook_remove_flags remove_flags)
03020 {
03021    struct ast_bridge_hook_dtmf *hook;
03022    int res;
03023 
03024    /* Allocate new hook and setup it's various variables */
03025    hook = (struct ast_bridge_hook_dtmf *) bridge_hook_generic(sizeof(*hook), callback,
03026       hook_pvt, destructor, remove_flags);
03027    if (!hook) {
03028       return -1;
03029    }
03030    hook->generic.type = AST_BRIDGE_HOOK_TYPE_DTMF;
03031    ast_copy_string(hook->dtmf.code, dtmf, sizeof(hook->dtmf.code));
03032 
03033    /* Once done we put it in the container. */
03034    res = ao2_link(features->dtmf_hooks, hook) ? 0 : -1;
03035    if (res) {
03036       /*
03037        * Could not link the hook into the container.
03038        *
03039        * Remove the hook_pvt destructor call from the hook since we
03040        * are returning failure to install the hook.
03041        */
03042       hook->generic.destructor = NULL;
03043    }
03044    ao2_ref(hook, -1);
03045 
03046    return res;
03047 }
03048 
03049 /*!
03050  * \internal
03051  * \brief Attach an other hook to a bridge features structure
03052  *
03053  * \param features Bridge features structure
03054  * \param callback Function to execute upon activation
03055  * \param hook_pvt Unique data
03056  * \param destructor Optional destructor callback for hook_pvt data
03057  * \param remove_flags Dictates what situations the hook should be removed.
03058  * \param type What type of hook is being attached.
03059  *
03060  * \retval 0 on success
03061  * \retval -1 on failure (The caller must cleanup any hook_pvt resources.)
03062  */
03063 static int bridge_other_hook(struct ast_bridge_features *features,
03064    ast_bridge_hook_callback callback,
03065    void *hook_pvt,
03066    ast_bridge_hook_pvt_destructor destructor,
03067    enum ast_bridge_hook_remove_flags remove_flags,
03068    enum ast_bridge_hook_type type)
03069 {
03070    struct ast_bridge_hook *hook;
03071    int res;
03072 
03073    /* Allocate new hook and setup it's various variables */
03074    hook = bridge_hook_generic(sizeof(*hook), callback, hook_pvt, destructor,
03075       remove_flags);
03076    if (!hook) {
03077       return -1;
03078    }
03079    hook->type = type;
03080 
03081    /* Once done we put it in the container. */
03082    res = ao2_link(features->other_hooks, hook) ? 0 : -1;
03083    if (res) {
03084       /*
03085        * Could not link the hook into the container.
03086        *
03087        * Remove the hook_pvt destructor call from the hook since we
03088        * are returning failure to install the hook.
03089        */
03090       hook->destructor = NULL;
03091    }
03092    ao2_ref(hook, -1);
03093 
03094    return res;
03095 }
03096 
03097 int ast_bridge_hangup_hook(struct ast_bridge_features *features,
03098    ast_bridge_hook_callback callback,
03099    void *hook_pvt,
03100    ast_bridge_hook_pvt_destructor destructor,
03101    enum ast_bridge_hook_remove_flags remove_flags)
03102 {
03103    return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
03104       AST_BRIDGE_HOOK_TYPE_HANGUP);
03105 }
03106 
03107 int ast_bridge_join_hook(struct ast_bridge_features *features,
03108    ast_bridge_hook_callback callback,
03109    void *hook_pvt,
03110    ast_bridge_hook_pvt_destructor destructor,
03111    enum ast_bridge_hook_remove_flags remove_flags)
03112 {
03113    return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
03114       AST_BRIDGE_HOOK_TYPE_JOIN);
03115 }
03116 
03117 int ast_bridge_leave_hook(struct ast_bridge_features *features,
03118    ast_bridge_hook_callback callback,
03119    void *hook_pvt,
03120    ast_bridge_hook_pvt_destructor destructor,
03121    enum ast_bridge_hook_remove_flags remove_flags)
03122 {
03123    return bridge_other_hook(features, callback, hook_pvt, destructor, remove_flags,
03124       AST_BRIDGE_HOOK_TYPE_LEAVE);
03125 }
03126 
03127 int ast_bridge_talk_detector_hook(struct ast_bridge_features *features,
03128    ast_bridge_talking_indicate_callback callback,
03129    void *hook_pvt,
03130    ast_bridge_hook_pvt_destructor destructor,
03131    enum ast_bridge_hook_remove_flags remove_flags)
03132 {
03133    ast_bridge_hook_callback hook_cb = (ast_bridge_hook_callback) callback;
03134 
03135    return bridge_other_hook(features, hook_cb, hook_pvt, destructor, remove_flags,
03136       AST_BRIDGE_HOOK_TYPE_TALK);
03137 }
03138 
03139 int ast_bridge_move_hook(struct ast_bridge_features *features,
03140    ast_bridge_move_indicate_callback callback,
03141    void *hook_pvt,
03142    ast_bridge_hook_pvt_destructor destructor,
03143    enum ast_bridge_hook_remove_flags remove_flags)
03144 {
03145    ast_bridge_hook_callback hook_cb = (ast_bridge_hook_callback) callback;
03146 
03147    return bridge_other_hook(features, hook_cb, hook_pvt, destructor, remove_flags,
03148       AST_BRIDGE_HOOK_TYPE_MOVE);
03149 }
03150 
03151 int ast_bridge_interval_hook(struct ast_bridge_features *features,
03152    enum ast_bridge_hook_timer_option flags,
03153    unsigned int interval,
03154    ast_bridge_hook_callback callback,
03155    void *hook_pvt,
03156    ast_bridge_hook_pvt_destructor destructor,
03157    enum ast_bridge_hook_remove_flags remove_flags)
03158 {
03159    struct ast_bridge_hook_timer *hook;
03160    int res;
03161 
03162    if (!features ||!interval || !callback) {
03163       return -1;
03164    }
03165 
03166    /* Allocate new hook and setup it's various variables */
03167    hook = (struct ast_bridge_hook_timer *) bridge_hook_generic(sizeof(*hook), callback,
03168       hook_pvt, destructor, remove_flags);
03169    if (!hook) {
03170       return -1;
03171    }
03172    hook->generic.type = AST_BRIDGE_HOOK_TYPE_TIMER;
03173    hook->timer.interval = interval;
03174    hook->timer.trip_time = ast_tvadd(ast_tvnow(), ast_samp2tv(interval, 1000));
03175    hook->timer.seqno = ast_atomic_fetchadd_int((int *) &features->interval_sequence, +1);
03176    hook->timer.flags = flags;
03177 
03178    ast_debug(1, "Putting interval hook %p with interval %u in the heap on features %p\n",
03179       hook, hook->timer.interval, features);
03180    ast_heap_wrlock(features->interval_hooks);
03181    res = ast_heap_push(features->interval_hooks, hook);
03182    ast_heap_unlock(features->interval_hooks);
03183    if (res) {
03184       /*
03185        * Could not push the hook into the heap
03186        *
03187        * Remove the hook_pvt destructor call from the hook since we
03188        * are returning failure to install the hook.
03189        */
03190       hook->generic.destructor = NULL;
03191       ao2_ref(hook, -1);
03192    }
03193 
03194    return res ? -1 : 0;
03195 }
03196 
03197 int ast_bridge_features_enable(struct ast_bridge_features *features,
03198    enum ast_bridge_builtin_feature feature,
03199    const char *dtmf,
03200    void *config,
03201    ast_bridge_hook_pvt_destructor destructor,
03202    enum ast_bridge_hook_remove_flags remove_flags)
03203 {
03204    if (ARRAY_LEN(builtin_features_handlers) <= feature
03205       || !builtin_features_handlers[feature]) {
03206       return -1;
03207    }
03208 
03209    /* If no alternate DTMF stream was provided use the default one */
03210    if (ast_strlen_zero(dtmf)) {
03211       dtmf = builtin_features_dtmf[feature];
03212       /* If no DTMF is still available (ie: it has been disabled) then error out now */
03213       if (ast_strlen_zero(dtmf)) {
03214          ast_debug(1, "Failed to enable built in feature %u on %p, no DTMF string is available for it.\n",
03215             feature, features);
03216          return -1;
03217       }
03218    }
03219 
03220    /*
03221     * The rest is basically pretty easy.  We create another hook
03222     * using the built in feature's DTMF callback.  Easy as pie.
03223     */
03224    return ast_bridge_dtmf_hook(features, dtmf, builtin_features_handlers[feature],
03225       config, destructor, remove_flags);
03226 }
03227 
03228 int ast_bridge_features_limits_construct(struct ast_bridge_features_limits *limits)
03229 {
03230    memset(limits, 0, sizeof(*limits));
03231 
03232    if (ast_string_field_init(limits, 256)) {
03233       return -1;
03234    }
03235 
03236    return 0;
03237 }
03238 
03239 void ast_bridge_features_limits_destroy(struct ast_bridge_features_limits *limits)
03240 {
03241    ast_string_field_free_memory(limits);
03242 }
03243 
03244 int ast_bridge_features_set_limits(struct ast_bridge_features *features,
03245    struct ast_bridge_features_limits *limits,
03246    enum ast_bridge_hook_remove_flags remove_flags)
03247 {
03248    if (builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_LIMITS]) {
03249       ast_bridge_builtin_set_limits_fn callback;
03250 
03251       callback = builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_LIMITS];
03252       return callback(features, limits, remove_flags);
03253    }
03254 
03255    ast_log(LOG_ERROR, "Attempted to set limits without an AST_BRIDGE_BUILTIN_INTERVAL_LIMITS callback registered.\n");
03256    return -1;
03257 }
03258 
03259 void ast_bridge_features_set_flag(struct ast_bridge_features *features, unsigned int flag)
03260 {
03261    ast_set_flag(&features->feature_flags, flag);
03262    features->usable = 1;
03263 }
03264 
03265 /*!
03266  * \internal
03267  * \brief ao2 object match hooks with appropriate remove_flags.
03268  * \since 12.0.0
03269  *
03270  * \param obj Feature hook object.
03271  * \param arg Removal flags
03272  * \param flags Not used
03273  *
03274  * \retval CMP_MATCH if hook's remove_flags match the removal flags set.
03275  * \retval 0 if not match.
03276  */
03277 static int hook_remove_match(void *obj, void *arg, int flags)
03278 {
03279    struct ast_bridge_hook *hook = obj;
03280    enum ast_bridge_hook_remove_flags *remove_flags = arg;
03281 
03282    if (ast_test_flag(&hook->remove_flags, *remove_flags)) {
03283       return CMP_MATCH;
03284    } else {
03285       return 0;
03286    }
03287 }
03288 
03289 /*!
03290  * \internal
03291  * \brief Remove all hooks with appropriate remove_flags in the container.
03292  * \since 12.0.0
03293  *
03294  * \param hooks Hooks container to work on.
03295  * \param remove_flags Determinator for whether hook is removed
03296  *
03297  * \return Nothing
03298  */
03299 static void hooks_remove_container(struct ao2_container *hooks, enum ast_bridge_hook_remove_flags remove_flags)
03300 {
03301    ao2_callback(hooks, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
03302       hook_remove_match, &remove_flags);
03303 }
03304 
03305 /*!
03306  * \internal
03307  * \brief Remove all hooks in the heap with appropriate remove_flags set.
03308  * \since 12.0.0
03309  *
03310  * \param hooks Hooks heap to work on.
03311  * \param remove_flags Determinator for whether hook is removed
03312  *
03313  * \return Nothing
03314  */
03315 static void hooks_remove_heap(struct ast_heap *hooks, enum ast_bridge_hook_remove_flags remove_flags)
03316 {
03317    struct ast_bridge_hook *hook;
03318    int changed;
03319 
03320    ast_heap_wrlock(hooks);
03321    do {
03322       int idx;
03323 
03324       changed = 0;
03325       for (idx = ast_heap_size(hooks); idx; --idx) {
03326          hook = ast_heap_peek(hooks, idx);
03327          if (ast_test_flag(&hook->remove_flags, remove_flags)) {
03328             ast_heap_remove(hooks, hook);
03329             ao2_ref(hook, -1);
03330             changed = 1;
03331          }
03332       }
03333    } while (changed);
03334    ast_heap_unlock(hooks);
03335 }
03336 
03337 void ast_bridge_features_remove(struct ast_bridge_features *features, enum ast_bridge_hook_remove_flags remove_flags)
03338 {
03339    hooks_remove_container(features->dtmf_hooks, remove_flags);
03340    hooks_remove_container(features->other_hooks, remove_flags);
03341    hooks_remove_heap(features->interval_hooks, remove_flags);
03342 }
03343 
03344 static int interval_hook_time_cmp(void *a, void *b)
03345 {
03346    struct ast_bridge_hook_timer *hook_a = a;
03347    struct ast_bridge_hook_timer *hook_b = b;
03348    int cmp;
03349 
03350    cmp = ast_tvcmp(hook_b->timer.trip_time, hook_a->timer.trip_time);
03351    if (cmp) {
03352       return cmp;
03353    }
03354 
03355    cmp = hook_b->timer.seqno - hook_a->timer.seqno;
03356    return cmp;
03357 }
03358 
03359 /*!
03360  * \internal
03361  * \brief DTMF hook container sort comparison function.
03362  * \since 12.0.0
03363  *
03364  * \param obj_left pointer to the (user-defined part) of an object.
03365  * \param obj_right pointer to the (user-defined part) of an object.
03366  * \param flags flags from ao2_callback()
03367  *   OBJ_POINTER - if set, 'obj_right', is an object.
03368  *   OBJ_KEY - if set, 'obj_right', is a search key item that is not an object.
03369  *   OBJ_PARTIAL_KEY - if set, 'obj_right', is a partial search key item that is not an object.
03370  *
03371  * \retval <0 if obj_left < obj_right
03372  * \retval =0 if obj_left == obj_right
03373  * \retval >0 if obj_left > obj_right
03374  */
03375 static int bridge_dtmf_hook_sort(const void *obj_left, const void *obj_right, int flags)
03376 {
03377    const struct ast_bridge_hook_dtmf *hook_left = obj_left;
03378    const struct ast_bridge_hook_dtmf *hook_right = obj_right;
03379    const char *right_key = obj_right;
03380    int cmp;
03381 
03382    switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
03383    default:
03384    case OBJ_POINTER:
03385       right_key = hook_right->dtmf.code;
03386       /* Fall through */
03387    case OBJ_KEY:
03388       cmp = strcasecmp(hook_left->dtmf.code, right_key);
03389       break;
03390    case OBJ_PARTIAL_KEY:
03391       cmp = strncasecmp(hook_left->dtmf.code, right_key, strlen(right_key));
03392       break;
03393    }
03394    return cmp;
03395 }
03396 
03397 /*! \brief Callback for merging hook ao2_containers */
03398 static int merge_container_cb(void *obj, void *data, int flags)
03399 {
03400    ao2_link(data, obj);
03401    return 0;
03402 }
03403 
03404 /*! \brief Wrapper for interval hooks that calls into the wrapped hook */
03405 static int interval_wrapper_cb(struct ast_bridge_channel *bridge_channel, void *obj)
03406 {
03407    struct ast_bridge_hook_timer *hook = obj;
03408 
03409    return hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
03410 }
03411 
03412 /*! \brief Destructor for the hook wrapper */
03413 static void interval_wrapper_pvt_dtor(void *obj)
03414 {
03415    ao2_cleanup(obj);
03416 }
03417 
03418 /*! \brief Wrap the provided interval hook and add it to features */
03419 static void wrap_hook(struct ast_bridge_features *features, struct ast_bridge_hook_timer *hook)
03420 {
03421    /* Break out of the current wrapper if it exists to avoid multiple layers */
03422    if (hook->generic.callback == interval_wrapper_cb) {
03423       hook = hook->generic.hook_pvt;
03424    }
03425 
03426    ast_bridge_interval_hook(features, hook->timer.flags, hook->timer.interval,
03427       interval_wrapper_cb, ao2_bump(hook), interval_wrapper_pvt_dtor,
03428       hook->generic.remove_flags.flags);
03429 }
03430 
03431 void ast_bridge_features_merge(struct ast_bridge_features *into, const struct ast_bridge_features *from)
03432 {
03433    struct ast_bridge_hook_timer *hook;
03434    int idx;
03435 
03436    /* Merge hook containers */
03437    ao2_callback(from->dtmf_hooks, 0, merge_container_cb, into->dtmf_hooks);
03438    ao2_callback(from->other_hooks, 0, merge_container_cb, into->other_hooks);
03439 
03440    /* Merge hook heaps */
03441    ast_heap_wrlock(from->interval_hooks);
03442    for (idx = 1; (hook = ast_heap_peek(from->interval_hooks, idx)); idx++) {
03443       wrap_hook(into, hook);
03444    }
03445    ast_heap_unlock(from->interval_hooks);
03446 
03447    /* Merge feature flags */
03448    into->feature_flags.flags |= from->feature_flags.flags;
03449    into->usable |= from->usable;
03450 
03451    into->mute |= from->mute;
03452    into->dtmf_passthrough |= from->dtmf_passthrough;
03453 }
03454 
03455 /* XXX ASTERISK-21271 make ast_bridge_features_init() static when make ast_bridge_join() requires features to be allocated. */
03456 int ast_bridge_features_init(struct ast_bridge_features *features)
03457 {
03458    /* Zero out the structure */
03459    memset(features, 0, sizeof(*features));
03460 
03461    /* Initialize the DTMF hooks container */
03462    features->dtmf_hooks = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX,
03463       AO2_CONTAINER_ALLOC_OPT_DUPS_REPLACE, bridge_dtmf_hook_sort, NULL);
03464    if (!features->dtmf_hooks) {
03465       return -1;
03466    }
03467 
03468    /* Initialize the miscellaneous other hooks container */
03469    features->other_hooks = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL,
03470       NULL);
03471    if (!features->other_hooks) {
03472       return -1;
03473    }
03474 
03475    /* Initialize the interval hooks heap */
03476    features->interval_hooks = ast_heap_create(8, interval_hook_time_cmp,
03477       offsetof(struct ast_bridge_hook_timer, timer.heap_index));
03478    if (!features->interval_hooks) {
03479       return -1;
03480    }
03481 
03482    features->dtmf_passthrough = 1;
03483 
03484    return 0;
03485 }
03486 
03487 /* XXX ASTERISK-21271 make ast_bridge_features_cleanup() static when make ast_bridge_join() requires features to be allocated. */
03488 void ast_bridge_features_cleanup(struct ast_bridge_features *features)
03489 {
03490    struct ast_bridge_hook_timer *hook;
03491 
03492    /* Destroy the interval hooks heap. */
03493    if (features->interval_hooks) {
03494       while ((hook = ast_heap_pop(features->interval_hooks))) {
03495          ao2_ref(hook, -1);
03496       }
03497       features->interval_hooks = ast_heap_destroy(features->interval_hooks);
03498    }
03499 
03500    /* Destroy the miscellaneous other hooks container. */
03501    ao2_cleanup(features->other_hooks);
03502    features->other_hooks = NULL;
03503 
03504    /* Destroy the DTMF hooks container. */
03505    ao2_cleanup(features->dtmf_hooks);
03506    features->dtmf_hooks = NULL;
03507 }
03508 
03509 void ast_bridge_features_destroy(struct ast_bridge_features *features)
03510 {
03511    if (!features) {
03512       return;
03513    }
03514    ast_bridge_features_cleanup(features);
03515    ast_free(features);
03516 }
03517 
03518 struct ast_bridge_features *ast_bridge_features_new(void)
03519 {
03520    struct ast_bridge_features *features;
03521 
03522    features = ast_malloc(sizeof(*features));
03523    if (features) {
03524       if (ast_bridge_features_init(features)) {
03525          ast_bridge_features_destroy(features);
03526          features = NULL;
03527       }
03528    }
03529 
03530    return features;
03531 }
03532 
03533 void ast_bridge_set_mixing_interval(struct ast_bridge *bridge, unsigned int mixing_interval)
03534 {
03535    ast_bridge_lock(bridge);
03536    bridge->softmix.internal_mixing_interval = mixing_interval;
03537    ast_bridge_unlock(bridge);
03538 }
03539 
03540 void ast_bridge_set_internal_sample_rate(struct ast_bridge *bridge, unsigned int sample_rate)
03541 {
03542    ast_bridge_lock(bridge);
03543    bridge->softmix.internal_sample_rate = sample_rate;
03544    ast_bridge_unlock(bridge);
03545 }
03546 
03547 static void cleanup_video_mode(struct ast_bridge *bridge)
03548 {
03549    switch (bridge->softmix.video_mode.mode) {
03550    case AST_BRIDGE_VIDEO_MODE_NONE:
03551       break;
03552    case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
03553       if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc) {
03554          ast_channel_unref(bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc);
03555       }
03556       break;
03557    case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
03558       if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc) {
03559          ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc);
03560       }
03561       if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc) {
03562          ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc);
03563       }
03564    }
03565    memset(&bridge->softmix.video_mode, 0, sizeof(bridge->softmix.video_mode));
03566 }
03567 
03568 void ast_bridge_set_single_src_video_mode(struct ast_bridge *bridge, struct ast_channel *video_src_chan)
03569 {
03570    ast_bridge_lock(bridge);
03571    cleanup_video_mode(bridge);
03572    bridge->softmix.video_mode.mode = AST_BRIDGE_VIDEO_MODE_SINGLE_SRC;
03573    bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc = ast_channel_ref(video_src_chan);
03574    ast_test_suite_event_notify("BRIDGE_VIDEO_MODE", "Message: video mode set to single source\r\nVideo Mode: %u\r\nVideo Channel: %s",
03575       bridge->softmix.video_mode.mode, ast_channel_name(video_src_chan));
03576    ast_indicate(video_src_chan, AST_CONTROL_VIDUPDATE);
03577    ast_bridge_unlock(bridge);
03578 }
03579 
03580 void ast_bridge_set_talker_src_video_mode(struct ast_bridge *bridge)
03581 {
03582    ast_bridge_lock(bridge);
03583    cleanup_video_mode(bridge);
03584    bridge->softmix.video_mode.mode = AST_BRIDGE_VIDEO_MODE_TALKER_SRC;
03585    ast_test_suite_event_notify("BRIDGE_VIDEO_MODE", "Message: video mode set to talker source\r\nVideo Mode: %u",
03586       bridge->softmix.video_mode.mode);
03587    ast_bridge_unlock(bridge);
03588 }
03589 
03590 void ast_bridge_update_talker_src_video_mode(struct ast_bridge *bridge, struct ast_channel *chan, int talker_energy, int is_keyframe)
03591 {
03592    struct ast_bridge_video_talker_src_data *data;
03593 
03594    /* If the channel doesn't support video, we don't care about it */
03595    if (!ast_format_cap_has_type(ast_channel_nativeformats(chan), AST_MEDIA_TYPE_VIDEO)) {
03596       return;
03597    }
03598 
03599    ast_bridge_lock(bridge);
03600    data = &bridge->softmix.video_mode.mode_data.talker_src_data;
03601 
03602    if (data->chan_vsrc == chan) {
03603       data->average_talking_energy = talker_energy;
03604    } else if ((data->average_talking_energy < talker_energy) && is_keyframe) {
03605       if (data->chan_old_vsrc) {
03606          ast_channel_unref(data->chan_old_vsrc);
03607       }
03608       if (data->chan_vsrc) {
03609          data->chan_old_vsrc = data->chan_vsrc;
03610          ast_indicate(data->chan_old_vsrc, AST_CONTROL_VIDUPDATE);
03611       }
03612       data->chan_vsrc = ast_channel_ref(chan);
03613       data->average_talking_energy = talker_energy;
03614       ast_test_suite_event_notify("BRIDGE_VIDEO_SRC", "Message: video source updated\r\nVideo Channel: %s", ast_channel_name(data->chan_vsrc));
03615       ast_indicate(data->chan_vsrc, AST_CONTROL_VIDUPDATE);
03616    } else if ((data->average_talking_energy < talker_energy) && !is_keyframe) {
03617       ast_indicate(chan, AST_CONTROL_VIDUPDATE);
03618    } else if (!data->chan_vsrc && is_keyframe) {
03619       data->chan_vsrc = ast_channel_ref(chan);
03620       data->average_talking_energy = talker_energy;
03621       ast_test_suite_event_notify("BRIDGE_VIDEO_SRC", "Message: video source updated\r\nVideo Channel: %s", ast_channel_name(data->chan_vsrc));
03622       ast_indicate(chan, AST_CONTROL_VIDUPDATE);
03623    } else if (!data->chan_old_vsrc && is_keyframe) {
03624       data->chan_old_vsrc = ast_channel_ref(chan);
03625       ast_indicate(chan, AST_CONTROL_VIDUPDATE);
03626    }
03627    ast_bridge_unlock(bridge);
03628 }
03629 
03630 int ast_bridge_number_video_src(struct ast_bridge *bridge)
03631 {
03632    int res = 0;
03633 
03634    ast_bridge_lock(bridge);
03635    switch (bridge->softmix.video_mode.mode) {
03636    case AST_BRIDGE_VIDEO_MODE_NONE:
03637       break;
03638    case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
03639       if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc) {
03640          res = 1;
03641       }
03642       break;
03643    case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
03644       if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc) {
03645          res++;
03646       }
03647       if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc) {
03648          res++;
03649       }
03650    }
03651    ast_bridge_unlock(bridge);
03652    return res;
03653 }
03654 
03655 int ast_bridge_is_video_src(struct ast_bridge *bridge, struct ast_channel *chan)
03656 {
03657    int res = 0;
03658 
03659    ast_bridge_lock(bridge);
03660    switch (bridge->softmix.video_mode.mode) {
03661    case AST_BRIDGE_VIDEO_MODE_NONE:
03662       break;
03663    case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
03664       if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc == chan) {
03665          res = 1;
03666       }
03667       break;
03668    case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
03669       if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc == chan) {
03670          res = 1;
03671       } else if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc == chan) {
03672          res = 2;
03673       }
03674 
03675    }
03676    ast_bridge_unlock(bridge);
03677    return res;
03678 }
03679 
03680 void ast_bridge_remove_video_src(struct ast_bridge *bridge, struct ast_channel *chan)
03681 {
03682    ast_bridge_lock(bridge);
03683    switch (bridge->softmix.video_mode.mode) {
03684    case AST_BRIDGE_VIDEO_MODE_NONE:
03685       break;
03686    case AST_BRIDGE_VIDEO_MODE_SINGLE_SRC:
03687       if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc == chan) {
03688          if (bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc) {
03689             ast_channel_unref(bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc);
03690          }
03691          bridge->softmix.video_mode.mode_data.single_src_data.chan_vsrc = NULL;
03692       }
03693       break;
03694    case AST_BRIDGE_VIDEO_MODE_TALKER_SRC:
03695       if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc == chan) {
03696          if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc) {
03697             ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc);
03698          }
03699          bridge->softmix.video_mode.mode_data.talker_src_data.chan_vsrc = NULL;
03700          bridge->softmix.video_mode.mode_data.talker_src_data.average_talking_energy = 0;
03701       }
03702       if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc == chan) {
03703          if (bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc) {
03704             ast_channel_unref(bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc);
03705          }
03706          bridge->softmix.video_mode.mode_data.talker_src_data.chan_old_vsrc = NULL;
03707       }
03708    }
03709    ast_bridge_unlock(bridge);
03710 }
03711 
03712 static int channel_hash(const void *obj, int flags)
03713 {
03714    const struct ast_channel *chan = obj;
03715    const char *name = obj;
03716    int hash;
03717 
03718    switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
03719    default:
03720    case OBJ_POINTER:
03721       name = ast_channel_name(chan);
03722       /* Fall through */
03723    case OBJ_KEY:
03724       hash = ast_str_hash(name);
03725       break;
03726    case OBJ_PARTIAL_KEY:
03727       /* Should never happen in hash callback. */
03728       ast_assert(0);
03729       hash = 0;
03730       break;
03731    }
03732    return hash;
03733 }
03734 
03735 static int channel_cmp(void *obj, void *arg, int flags)
03736 {
03737    const struct ast_channel *left = obj;
03738    const struct ast_channel *right = arg;
03739    const char *right_name = arg;
03740    int cmp;
03741 
03742    switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
03743    default:
03744    case OBJ_POINTER:
03745       right_name = ast_channel_name(right);
03746       /* Fall through */
03747    case OBJ_KEY:
03748       cmp = strcmp(ast_channel_name(left), right_name);
03749       break;
03750    case OBJ_PARTIAL_KEY:
03751       cmp = strncmp(ast_channel_name(left), right_name, strlen(right_name));
03752       break;
03753    }
03754    return cmp ? 0 : CMP_MATCH;
03755 }
03756 
03757 struct ao2_container *ast_bridge_peers_nolock(struct ast_bridge *bridge)
03758 {
03759    struct ao2_container *channels;
03760    struct ast_bridge_channel *iter;
03761 
03762    channels = ao2_container_alloc_options(AO2_ALLOC_OPT_LOCK_NOLOCK,
03763       13, channel_hash, channel_cmp);
03764    if (!channels) {
03765       return NULL;
03766    }
03767 
03768    AST_LIST_TRAVERSE(&bridge->channels, iter, entry) {
03769       ao2_link(channels, iter->chan);
03770    }
03771 
03772    return channels;
03773 }
03774 
03775 struct ao2_container *ast_bridge_peers(struct ast_bridge *bridge)
03776 {
03777    struct ao2_container *channels;
03778 
03779    ast_bridge_lock(bridge);
03780    channels = ast_bridge_peers_nolock(bridge);
03781    ast_bridge_unlock(bridge);
03782 
03783    return channels;
03784 }
03785 
03786 struct ast_channel *ast_bridge_peer_nolock(struct ast_bridge *bridge, struct ast_channel *chan)
03787 {
03788    struct ast_channel *peer = NULL;
03789    struct ast_bridge_channel *iter;
03790 
03791    /* Asking for the peer channel only makes sense on a two-party bridge. */
03792    if (bridge->num_channels == 2
03793       && bridge->technology->capabilities
03794          & (AST_BRIDGE_CAPABILITY_NATIVE | AST_BRIDGE_CAPABILITY_1TO1MIX)) {
03795       int in_bridge = 0;
03796 
03797       AST_LIST_TRAVERSE(&bridge->channels, iter, entry) {
03798          if (iter->chan != chan) {
03799             peer = iter->chan;
03800          } else {
03801             in_bridge = 1;
03802          }
03803       }
03804       if (in_bridge && peer) {
03805          ast_channel_ref(peer);
03806       } else {
03807          peer = NULL;
03808       }
03809    }
03810 
03811    return peer;
03812 }
03813 
03814 struct ast_channel *ast_bridge_peer(struct ast_bridge *bridge, struct ast_channel *chan)
03815 {
03816    struct ast_channel *peer;
03817 
03818    ast_bridge_lock(bridge);
03819    peer = ast_bridge_peer_nolock(bridge, chan);
03820    ast_bridge_unlock(bridge);
03821 
03822    return peer;
03823 }
03824 
03825 /*!
03826  * \internal
03827  * \brief Transfer an entire bridge to a specific destination.
03828  *
03829  * This creates a local channel to dial out and swaps the called local channel
03830  * with the transferer channel. By doing so, all participants in the bridge are
03831  * connected to the specified destination.
03832  *
03833  * While this means of transferring would work for both two-party and multi-party
03834  * bridges, this method is only used for multi-party bridges since this method would
03835  * be less efficient for two-party bridges.
03836  *
03837  * \param is_external Whether the transfer is externally initiated
03838  * \param transferer The channel performing a transfer
03839  * \param bridge The bridge where the transfer is being performed
03840  * \param exten The destination extension for the blind transfer
03841  * \param context The destination context for the blind transfer
03842  * \param transferee The party being transferred if there is only one
03843  * \param new_channel_cb Callback to call on channel that is created to
03844  *        facilitate the blind transfer.
03845  * \param user_data_wrapper User-provided data needed in new_channel_cb
03846  * \param transfer_message The Stasis publication for this transfer.
03847  *
03848  * \return The success or failure of the operation
03849  */
03850 static enum ast_transfer_result blind_transfer_bridge(int is_external,
03851       struct ast_channel *transferer, struct ast_bridge *bridge,
03852       const char *exten, const char *context, struct ast_channel *transferee,
03853       transfer_channel_cb new_channel_cb,
03854       struct transfer_channel_data *user_data_wrapper,
03855       struct ast_blind_transfer_message *transfer_message)
03856 {
03857    struct ast_channel *local;
03858    char chan_name[AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2];
03859    int cause;
03860 
03861    snprintf(chan_name, sizeof(chan_name), "%s@%s", exten, context);
03862    local = ast_request("Local", ast_channel_nativeformats(transferer), NULL, transferer,
03863          chan_name, &cause);
03864    if (!local) {
03865       return AST_BRIDGE_TRANSFER_FAIL;
03866    }
03867 
03868    ast_channel_lock_both(local, transferer);
03869    ast_channel_req_accountcodes(local, transferer, AST_CHANNEL_REQUESTOR_REPLACEMENT);
03870 
03871    transfer_message->replace_channel = ast_channel_snapshot_get_latest(ast_channel_uniqueid(local));
03872    if (!transfer_message->replace_channel) {
03873       ast_hangup(local);
03874       return AST_BRIDGE_TRANSFER_FAIL;
03875    }
03876 
03877    pbx_builtin_setvar_helper(local, BLINDTRANSFER, ast_channel_name(transferer));
03878    ast_channel_unlock(local);
03879    ast_channel_unlock(transferer);
03880 
03881    if (new_channel_cb) {
03882       new_channel_cb(local, user_data_wrapper, AST_BRIDGE_TRANSFER_MULTI_PARTY);
03883    }
03884 
03885    if (ast_call(local, chan_name, 0)) {
03886       ast_hangup(local);
03887       return AST_BRIDGE_TRANSFER_FAIL;
03888    }
03889 
03890    if (ast_bridge_impart(bridge, local, transferer, NULL,
03891       AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
03892       ast_hangup(local);
03893       return AST_BRIDGE_TRANSFER_FAIL;
03894    }
03895 
03896    return AST_BRIDGE_TRANSFER_SUCCESS;
03897 }
03898 
03899 /*!
03900  * \internal
03901  * \brief Get the transferee channel
03902  *
03903  * This is only applicable to cases where a transfer is occurring on a
03904  * two-party bridge. The channels container passed in is expected to only
03905  * contain two channels, the transferer and the transferee. The transferer
03906  * channel is passed in as a parameter to ensure we don't return it as
03907  * the transferee channel.
03908  *
03909  * \param channels A two-channel container containing the transferer and transferee
03910  * \param transferer The party that is transfering the call
03911  * \return The party that is being transferred
03912  */
03913 static struct ast_channel *get_transferee(struct ao2_container *channels, struct ast_channel *transferer)
03914 {
03915    struct ao2_iterator channel_iter;
03916    struct ast_channel *transferee;
03917 
03918    for (channel_iter = ao2_iterator_init(channels, 0);
03919          (transferee = ao2_iterator_next(&channel_iter));
03920          ao2_cleanup(transferee)) {
03921       if (transferee != transferer) {
03922          break;
03923       }
03924    }
03925 
03926    ao2_iterator_destroy(&channel_iter);
03927    return transferee;
03928 }
03929 
03930 /*!
03931  * \brief Perform an attended transfer of a bridge
03932  *
03933  * This performs an attended transfer of an entire bridge to a target.
03934  * The target varies, depending on what bridges exist during the transfer
03935  * attempt.
03936  *
03937  * If two bridges exist, then a local channel is created to link the two
03938  * bridges together.
03939  *
03940  * If only one bridge exists, then a local channel is created with one end
03941  * placed into the existing bridge and the other end masquerading into
03942  * the unbridged channel.
03943  *
03944  * \param chan1 Transferer channel. Guaranteed to be bridged.
03945  * \param chan2 Other transferer channel. May or may not be bridged.
03946  * \param bridge1 Bridge that chan1 is in. Guaranteed to be non-NULL.
03947  * \param bridge2 Bridge that chan2 is in. If NULL, then chan2 is not bridged.
03948  * \param publication Data to publish for a stasis attended transfer message.
03949  * \retval AST_BRIDGE_TRANSFER_FAIL Internal error occurred
03950  * \retval AST_BRIDGE_TRANSFER_SUCCESS Succesfully transferred the bridge
03951  */
03952 static enum ast_transfer_result attended_transfer_bridge(struct ast_channel *chan1,
03953       struct ast_channel *chan2, struct ast_bridge *bridge1, struct ast_bridge *bridge2,
03954       struct ast_attended_transfer_message *transfer_msg)
03955 {
03956    static const char *dest = "_attended@transfer/m";
03957    struct ast_channel *local_chan;
03958    int cause;
03959    int res;
03960    const char *app = NULL;
03961 
03962    local_chan = ast_request("Local", ast_channel_nativeformats(chan1), NULL, chan1,
03963          dest, &cause);
03964    if (!local_chan) {
03965       return AST_BRIDGE_TRANSFER_FAIL;
03966    }
03967 
03968    ast_channel_lock_both(local_chan, chan1);
03969    ast_channel_req_accountcodes(local_chan, chan1, AST_CHANNEL_REQUESTOR_REPLACEMENT);
03970    pbx_builtin_setvar_helper(local_chan, ATTENDEDTRANSFER, ast_channel_name(chan1));
03971    ast_channel_unlock(local_chan);
03972    ast_channel_unlock(chan1);
03973 
03974    if (bridge2) {
03975       res = ast_local_setup_bridge(local_chan, bridge2, chan2, NULL);
03976    } else {
03977       app = ast_strdupa(ast_channel_appl(chan2));
03978       res = ast_local_setup_masquerade(local_chan, chan2);
03979    }
03980 
03981    if (res) {
03982       ast_hangup(local_chan);
03983       return AST_BRIDGE_TRANSFER_FAIL;
03984    }
03985 
03986    if (ast_call(local_chan, dest, 0)) {
03987       ast_hangup(local_chan);
03988       return AST_BRIDGE_TRANSFER_FAIL;
03989    }
03990 
03991    /* Get a ref for use later since this one is being stolen */
03992    ao2_ref(local_chan, +1);
03993    if (ast_bridge_impart(bridge1, local_chan, chan1, NULL,
03994       AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
03995       ast_hangup(local_chan);
03996       ao2_cleanup(local_chan);
03997       return AST_BRIDGE_TRANSFER_FAIL;
03998    }
03999 
04000    if (bridge2) {
04001       RAII_VAR(struct ast_channel *, local_chan2, NULL, ao2_cleanup);
04002       struct ast_channel *locals[2];
04003 
04004       ast_channel_lock(local_chan);
04005       local_chan2 = ast_local_get_peer(local_chan);
04006       ast_channel_unlock(local_chan);
04007 
04008       ast_assert(local_chan2 != NULL);
04009 
04010       locals[0] = local_chan;
04011       locals[1] = local_chan2;
04012 
04013       ast_attended_transfer_message_add_link(transfer_msg, locals);
04014    } else {
04015       ast_attended_transfer_message_add_app(transfer_msg, app, local_chan);
04016    }
04017 
04018    ao2_cleanup(local_chan);
04019    return AST_BRIDGE_TRANSFER_SUCCESS;
04020 }
04021 
04022 static enum ast_transfer_result try_parking(struct ast_channel *transferer,
04023    const char *context, const char *exten, transfer_channel_cb new_channel_cb,
04024    struct transfer_channel_data *user_data_wrapper)
04025 {
04026    RAII_VAR(struct ast_bridge_channel *, transferer_bridge_channel, NULL, ao2_cleanup);
04027 
04028    if (!ast_parking_provider_registered()) {
04029       return AST_BRIDGE_TRANSFER_FAIL;
04030    }
04031 
04032    ast_channel_lock(transferer);
04033    transferer_bridge_channel = ast_channel_get_bridge_channel(transferer);
04034    ast_channel_unlock(transferer);
04035 
04036    if (!transferer_bridge_channel) {
04037       return AST_BRIDGE_TRANSFER_FAIL;
04038    }
04039 
04040    if (ast_parking_blind_transfer_park(transferer_bridge_channel,
04041       context, exten, new_channel_cb, user_data_wrapper)) {
04042       return AST_BRIDGE_TRANSFER_FAIL;
04043    }
04044 
04045    return AST_BRIDGE_TRANSFER_SUCCESS;
04046 }
04047 
04048 void ast_bridge_set_transfer_variables(struct ast_channel *chan, const char *value, int attended)
04049 {
04050    char *writevar;
04051    char *erasevar;
04052 
04053    if (attended) {
04054       writevar = ATTENDEDTRANSFER;
04055       erasevar = BLINDTRANSFER;
04056    } else {
04057       writevar = BLINDTRANSFER;
04058       erasevar = ATTENDEDTRANSFER;
04059    }
04060 
04061    pbx_builtin_setvar_helper(chan, writevar, value);
04062    pbx_builtin_setvar_helper(chan, erasevar, NULL);
04063 }
04064 
04065 /*!
04066  * \internal
04067  * \brief Set the transfer variable as appropriate on channels involved in the transfer
04068  *
04069  * The transferer channel will have its variable set the same as its BRIDGEPEER
04070  * variable. This will account for all channels that it is bridged to. The other channels
04071  * involved in the transfer will have their variable set to the transferer
04072  * channel's name.
04073  *
04074  * \param transferer The channel performing the transfer
04075  * \param channels The channels belonging to the bridge
04076  * \param is_attended false  set BLINDTRANSFER and unset ATTENDEDTRANSFER
04077  *                    true   set ATTENDEDTRANSFER and unset BLINDTRANSFER
04078  */
04079 static void set_transfer_variables_all(struct ast_channel *transferer, struct ao2_container *channels, int is_attended)
04080 {
04081    struct ao2_iterator iter;
04082    struct ast_channel *chan;
04083    const char *transferer_name;
04084    const char *transferer_bridgepeer;
04085 
04086    ast_channel_lock(transferer);
04087    transferer_name = ast_strdupa(ast_channel_name(transferer));
04088    transferer_bridgepeer = ast_strdupa(S_OR(pbx_builtin_getvar_helper(transferer, "BRIDGEPEER"), ""));
04089    ast_channel_unlock(transferer);
04090 
04091    for (iter = ao2_iterator_init(channels, 0);
04092          (chan = ao2_iterator_next(&iter));
04093          ao2_cleanup(chan)) {
04094       if (chan == transferer) {
04095          ast_bridge_set_transfer_variables(chan, transferer_bridgepeer, is_attended);
04096       } else {
04097          ast_bridge_set_transfer_variables(chan, transferer_name, is_attended);
04098       }
04099    }
04100 
04101    ao2_iterator_destroy(&iter);
04102 }
04103 
04104 static struct ast_bridge *acquire_bridge(struct ast_channel *chan)
04105 {
04106    struct ast_bridge *bridge;
04107 
04108    ast_channel_lock(chan);
04109    bridge = ast_channel_get_bridge(chan);
04110    ast_channel_unlock(chan);
04111 
04112    if (bridge
04113       && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_MASQUERADE_ONLY)) {
04114       ao2_ref(bridge, -1);
04115       bridge = NULL;
04116    }
04117 
04118    return bridge;
04119 }
04120 
04121 enum ast_transfer_result ast_bridge_transfer_blind(int is_external,
04122       struct ast_channel *transferer, const char *exten, const char *context,
04123       transfer_channel_cb new_channel_cb, void *user_data)
04124 {
04125    RAII_VAR(struct ast_bridge *, bridge, NULL, ao2_cleanup);
04126    RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
04127    RAII_VAR(struct ao2_container *, channels, NULL, ao2_cleanup);
04128    RAII_VAR(struct ast_channel *, transferee, NULL, ast_channel_cleanup);
04129    RAII_VAR(struct transfer_channel_data *, user_data_wrapper, NULL, ao2_cleanup);
04130    RAII_VAR(struct ast_blind_transfer_message *, transfer_message, NULL, ao2_cleanup);
04131    int do_bridge_transfer;
04132    int transfer_prohibited;
04133    enum ast_transfer_result transfer_result;
04134 
04135    transfer_message = ast_blind_transfer_message_create(is_external, transferer, exten, context);
04136    if (!transfer_message) {
04137       /* Out of memory. Not even possible to publish a Stasis message about the
04138        * failure
04139        */
04140       ast_log(LOG_ERROR, "Unable to allocate memory for blind transfer publication from %s\n",
04141             ast_channel_name(transferer));
04142       return AST_BRIDGE_TRANSFER_FAIL;
04143    }
04144 
04145    bridge = acquire_bridge(transferer);
04146    if (!bridge) {
04147       transfer_result = AST_BRIDGE_TRANSFER_INVALID;
04148       goto publish;
04149    }
04150 
04151    ast_bridge_lock(bridge);
04152    transfer_message->bridge = ast_bridge_snapshot_create(bridge);
04153    ast_bridge_unlock(bridge);
04154    if (!transfer_message->bridge) {
04155       transfer_result = AST_BRIDGE_TRANSFER_FAIL;
04156       goto publish;
04157    }
04158 
04159    transferee = ast_bridge_peer(bridge, transferer);
04160    if (transferee) {
04161       transfer_message->transferee = ast_channel_snapshot_get_latest(ast_channel_uniqueid(transferee));
04162       if (!transfer_message->transferee) {
04163          transfer_result = AST_BRIDGE_TRANSFER_FAIL;
04164          goto publish;
04165       }
04166    }
04167 
04168    ast_channel_lock(transferer);
04169    bridge_channel = ast_channel_get_bridge_channel(transferer);
04170    ast_channel_unlock(transferer);
04171    if (!bridge_channel) {
04172       transfer_result = AST_BRIDGE_TRANSFER_INVALID;
04173       goto publish;
04174    }
04175 
04176    user_data_wrapper = ao2_alloc(sizeof(*user_data_wrapper), NULL);
04177    if (!user_data_wrapper) {
04178       transfer_result = AST_BRIDGE_TRANSFER_FAIL;
04179       goto publish;
04180    }
04181 
04182    user_data_wrapper->data = user_data;
04183 
04184    /* Take off hold if they are on hold. */
04185    ast_bridge_channel_write_unhold(bridge_channel);
04186 
04187    transfer_result = try_parking(transferer, context, exten, new_channel_cb, user_data_wrapper);
04188    if (transfer_result == AST_BRIDGE_TRANSFER_SUCCESS) {
04189       goto publish;
04190    }
04191 
04192    /* Since parking didn't take control of the user_data_wrapper, we are just going to raise the completed flag now. */
04193    user_data_wrapper->completed = 1;
04194 
04195    {
04196       SCOPED_LOCK(lock, bridge, ast_bridge_lock, ast_bridge_unlock);
04197 
04198       channels = ast_bridge_peers_nolock(bridge);
04199       if (!channels) {
04200          transfer_result = AST_BRIDGE_TRANSFER_FAIL;
04201          goto publish;
04202       }
04203       if (ao2_container_count(channels) <= 1) {
04204          transfer_result = AST_BRIDGE_TRANSFER_INVALID;
04205          goto publish;
04206       }
04207       transfer_prohibited = ast_test_flag(&bridge->feature_flags,
04208             AST_BRIDGE_FLAG_TRANSFER_PROHIBITED);
04209       do_bridge_transfer = ast_test_flag(&bridge->feature_flags,
04210             AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY) ||
04211             ao2_container_count(channels) > 2;
04212    }
04213 
04214    if (transfer_prohibited) {
04215       transfer_result = AST_BRIDGE_TRANSFER_NOT_PERMITTED;
04216       goto publish;
04217    }
04218 
04219    set_transfer_variables_all(transferer, channels, 0);
04220 
04221    if (do_bridge_transfer) {
04222       transfer_result = blind_transfer_bridge(is_external, transferer, bridge,
04223          exten, context, transferee, new_channel_cb, user_data_wrapper, transfer_message);
04224       goto publish;
04225    }
04226 
04227    /* Reaching this portion means that we're dealing with a two-party bridge */
04228 
04229    if (!transferee) {
04230       transfer_result = AST_BRIDGE_TRANSFER_FAIL;
04231       goto publish;
04232    }
04233 
04234    if (bridge_channel_internal_queue_blind_transfer(transferee, exten, context,
04235             new_channel_cb, user_data_wrapper)) {
04236       transfer_result = AST_BRIDGE_TRANSFER_FAIL;
04237       goto publish;
04238    }
04239 
04240    ast_bridge_remove(bridge, transferer);
04241    transfer_result = AST_BRIDGE_TRANSFER_SUCCESS;
04242 
04243 publish:
04244    transfer_message->result = transfer_result;
04245    ast_bridge_publish_blind_transfer(transfer_message);
04246    return transfer_result;
04247 }
04248 
04249 /*!
04250  * \internal
04251  * \brief Performs an attended transfer by moving a channel from one bridge to another
04252  *
04253  * The channel that is bridged to the source_channel is moved into the dest_bridge from
04254  * the source_bridge_channel's bridge. The swap_channel is swapped out of the dest_bridge and placed in
04255  * the source_bridge_channel's bridge.
04256  *
04257  * \note dest_bridge and source_bridge_channel's bridge MUST be locked before calling this function.
04258  *
04259  * \param dest_bridge The final bridge for the attended transfer
04260  * \param source_channel Channel who is bridged to the channel that will move
04261  * \param swap_channel Channel to be swapped out of the dest_bridge
04262  * \return The success or failure of the swap attempt
04263  */
04264 static enum ast_transfer_result bridge_swap_attended_transfer(struct ast_bridge *dest_bridge,
04265       struct ast_bridge_channel *source_bridge_channel, struct ast_channel *swap_channel)
04266 {
04267    struct ast_bridge_channel *bridged_to_source;
04268 
04269    bridged_to_source = ast_bridge_channel_peer(source_bridge_channel);
04270    if (bridged_to_source
04271       && bridged_to_source->state == BRIDGE_CHANNEL_STATE_WAIT
04272       && !ast_test_flag(&bridged_to_source->features->feature_flags,
04273          AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
04274       bridged_to_source->swap = swap_channel;
04275       if (bridge_do_move(dest_bridge, bridged_to_source, 1, 0)) {
04276          return AST_BRIDGE_TRANSFER_FAIL;
04277       }
04278       /* Must kick the source channel out of its bridge. */
04279       ast_bridge_channel_leave_bridge(source_bridge_channel,
04280          BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, AST_CAUSE_NORMAL_CLEARING);
04281       return AST_BRIDGE_TRANSFER_SUCCESS;
04282    } else {
04283       return AST_BRIDGE_TRANSFER_INVALID;
04284    }
04285 }
04286 
04287 /*!
04288  * \internal
04289  * \brief Function that performs an attended transfer when both transferer channels are bridged
04290  *
04291  * The method by which the transfer is performed is dependent on whether the bridges allow for
04292  * optimization to occur between them. If no optimization is permitted, then an unreal channel
04293  * is placed as a link between the two bridges. If optimization is permitted, then that means
04294  * we are free to perform move or merge operations in order to perform the transfer.
04295  *
04296  * \note to_transferee_bridge and to_target_bridge MUST be locked before calling this function
04297  *
04298  * \param to_transferee The channel that is bridged to the transferee
04299  * \param to_transferee_bridge_channel to_transferee's bridge_channel
04300  * \param to_transfer_target The channel that is bridged to the transfer target
04301  * \param to_target_bridge_channel to_transfer_target's bridge_channel
04302  * \param to_transferee_bridge The bridge between to_transferee and the transferee
04303  * \param to_target_bridge The bridge between to_transfer_target and the transfer_target
04304  * \param publication Data to publish for a stasis attended transfer message
04305  * \return The success or failure of the attended transfer
04306  */
04307 static enum ast_transfer_result two_bridge_attended_transfer(struct ast_channel *to_transferee,
04308       struct ast_bridge_channel *to_transferee_bridge_channel,
04309       struct ast_channel *to_transfer_target,
04310       struct ast_bridge_channel *to_target_bridge_channel,
04311       struct ast_bridge *to_transferee_bridge, struct ast_bridge *to_target_bridge,
04312       struct ast_attended_transfer_message *transfer_msg)
04313 {
04314    struct ast_bridge_channel *kick_me[] = {
04315          to_transferee_bridge_channel,
04316          to_target_bridge_channel,
04317    };
04318    enum ast_transfer_result res;
04319    struct ast_bridge *final_bridge = NULL;
04320    RAII_VAR(struct ao2_container *, channels, NULL, ao2_cleanup);
04321 
04322    channels = ast_bridge_peers_nolock(to_transferee_bridge);
04323 
04324    if (!channels) {
04325       res = AST_BRIDGE_TRANSFER_FAIL;
04326       goto end;
04327    }
04328 
04329    set_transfer_variables_all(to_transferee, channels, 1);
04330 
04331    switch (ast_bridges_allow_optimization(to_transferee_bridge, to_target_bridge)) {
04332    case AST_BRIDGE_OPTIMIZE_SWAP_TO_CHAN_BRIDGE:
04333       final_bridge = to_transferee_bridge;
04334       res = bridge_swap_attended_transfer(to_transferee_bridge, to_target_bridge_channel, to_transferee);
04335       goto end;
04336    case AST_BRIDGE_OPTIMIZE_SWAP_TO_PEER_BRIDGE:
04337       final_bridge = to_target_bridge;
04338       res = bridge_swap_attended_transfer(to_target_bridge, to_transferee_bridge_channel, to_transfer_target);
04339       goto end;
04340    case AST_BRIDGE_OPTIMIZE_MERGE_TO_CHAN_BRIDGE:
04341       final_bridge = to_transferee_bridge;
04342       bridge_do_merge(to_transferee_bridge, to_target_bridge, kick_me, ARRAY_LEN(kick_me), 0);
04343       res = AST_BRIDGE_TRANSFER_SUCCESS;
04344       goto end;
04345    case AST_BRIDGE_OPTIMIZE_MERGE_TO_PEER_BRIDGE:
04346       final_bridge = to_target_bridge;
04347       bridge_do_merge(to_target_bridge, to_transferee_bridge, kick_me, ARRAY_LEN(kick_me), 0);
04348       res = AST_BRIDGE_TRANSFER_SUCCESS;
04349       goto end;
04350    case AST_BRIDGE_OPTIMIZE_PROHIBITED:
04351    default:
04352       /* Just because optimization wasn't doable doesn't necessarily mean
04353        * that we can actually perform the transfer. Some reasons for non-optimization
04354        * indicate bridge invalidity, so let's check those before proceeding.
04355        */
04356       if (to_transferee_bridge->inhibit_merge || to_transferee_bridge->dissolved ||
04357             to_target_bridge->inhibit_merge || to_target_bridge->dissolved) {
04358          return AST_BRIDGE_TRANSFER_INVALID;
04359       }
04360 
04361       return attended_transfer_bridge(to_transferee, to_transfer_target,
04362          to_transferee_bridge, to_target_bridge, transfer_msg);
04363    }
04364 
04365 end:
04366    if (res == AST_BRIDGE_TRANSFER_SUCCESS) {
04367       ast_attended_transfer_message_add_merge(transfer_msg, final_bridge);
04368    }
04369 
04370    return res;
04371 }
04372 
04373 enum ast_transfer_result ast_bridge_transfer_attended(struct ast_channel *to_transferee,
04374       struct ast_channel *to_transfer_target)
04375 {
04376    RAII_VAR(struct ast_bridge *, to_transferee_bridge, NULL, ao2_cleanup);
04377    RAII_VAR(struct ast_bridge *, to_target_bridge, NULL, ao2_cleanup);
04378    RAII_VAR(struct ast_bridge_channel *, to_transferee_bridge_channel, NULL, ao2_cleanup);
04379    RAII_VAR(struct ast_bridge_channel *, to_target_bridge_channel, NULL, ao2_cleanup);
04380    RAII_VAR(struct ao2_container *, channels, NULL, ao2_cleanup);
04381    RAII_VAR(struct ast_channel *, transferee, NULL, ao2_cleanup);
04382    RAII_VAR(struct ast_attended_transfer_message *, transfer_msg, NULL, ao2_cleanup);
04383    struct ast_bridge *the_bridge = NULL;
04384    struct ast_channel *chan_bridged;
04385    struct ast_channel *chan_unbridged;
04386    int transfer_prohibited;
04387    int do_bridge_transfer;
04388    enum ast_transfer_result res;
04389    const char *app = NULL;
04390 
04391    to_transferee_bridge = acquire_bridge(to_transferee);
04392    to_target_bridge = acquire_bridge(to_transfer_target);
04393 
04394    transfer_msg = ast_attended_transfer_message_create(1, to_transferee, to_transferee_bridge,
04395          to_transfer_target, to_target_bridge, NULL, NULL);
04396    if (!transfer_msg) {
04397       ast_log(LOG_ERROR, "Unable to create Stasis publication for attended transfer from %s\n",
04398             ast_channel_name(to_transferee));
04399       return AST_BRIDGE_TRANSFER_FAIL;
04400    }
04401 
04402    /* They can't both be unbridged, you silly goose! */
04403    if (!to_transferee_bridge && !to_target_bridge) {
04404       res = AST_BRIDGE_TRANSFER_INVALID;
04405       goto end;
04406    }
04407 
04408    ast_channel_lock(to_transferee);
04409    to_transferee_bridge_channel = ast_channel_get_bridge_channel(to_transferee);
04410    ast_channel_unlock(to_transferee);
04411 
04412    ast_channel_lock(to_transfer_target);
04413    to_target_bridge_channel = ast_channel_get_bridge_channel(to_transfer_target);
04414    ast_channel_unlock(to_transfer_target);
04415 
04416    if (to_transferee_bridge_channel) {
04417       /* Take off hold if they are on hold. */
04418       ast_bridge_channel_write_unhold(to_transferee_bridge_channel);
04419    }
04420 
04421    if (to_target_bridge_channel) {
04422       const char *target_complete_sound;
04423 
04424       /* Take off hold if they are on hold. */
04425       ast_bridge_channel_write_unhold(to_target_bridge_channel);
04426 
04427       /* Is there a courtesy sound to play to the target? */
04428       ast_channel_lock(to_transfer_target);
04429       target_complete_sound = pbx_builtin_getvar_helper(to_transfer_target,
04430          "ATTENDED_TRANSFER_COMPLETE_SOUND");
04431       if (!ast_strlen_zero(target_complete_sound)) {
04432          target_complete_sound = ast_strdupa(target_complete_sound);
04433       } else {
04434          target_complete_sound = NULL;
04435       }
04436       ast_channel_unlock(to_transfer_target);
04437       if (!target_complete_sound) {
04438          ast_channel_lock(to_transferee);
04439          target_complete_sound = pbx_builtin_getvar_helper(to_transferee,
04440             "ATTENDED_TRANSFER_COMPLETE_SOUND");
04441          if (!ast_strlen_zero(target_complete_sound)) {
04442             target_complete_sound = ast_strdupa(target_complete_sound);
04443          } else {
04444             target_complete_sound = NULL;
04445          }
04446          ast_channel_unlock(to_transferee);
04447       }
04448       if (target_complete_sound) {
04449          ast_bridge_channel_write_playfile(to_target_bridge_channel, NULL,
04450             target_complete_sound, NULL);
04451       }
04452    }
04453 
04454    /* Let's get the easy one out of the way first */
04455    if (to_transferee_bridge && to_target_bridge) {
04456 
04457       if (!to_transferee_bridge_channel || !to_target_bridge_channel) {
04458          res = AST_BRIDGE_TRANSFER_INVALID;
04459          goto end;
04460       }
04461 
04462       ast_bridge_lock_both(to_transferee_bridge, to_target_bridge);
04463       res = two_bridge_attended_transfer(to_transferee, to_transferee_bridge_channel,
04464             to_transfer_target, to_target_bridge_channel,
04465             to_transferee_bridge, to_target_bridge, transfer_msg);
04466       ast_bridge_unlock(to_transferee_bridge);
04467       ast_bridge_unlock(to_target_bridge);
04468 
04469       ast_softhangup(to_transfer_target, AST_SOFTHANGUP_DEV);
04470       goto end;
04471    }
04472 
04473    the_bridge = to_transferee_bridge ?: to_target_bridge;
04474    chan_bridged = to_transferee_bridge ? to_transferee : to_transfer_target;
04475    chan_unbridged = to_transferee_bridge ? to_transfer_target : to_transferee;
04476 
04477    {
04478       int chan_count;
04479       SCOPED_LOCK(lock, the_bridge, ast_bridge_lock, ast_bridge_unlock);
04480 
04481       channels = ast_bridge_peers_nolock(the_bridge);
04482       if (!channels) {
04483          res = AST_BRIDGE_TRANSFER_FAIL;
04484          goto end;
04485       }
04486       chan_count = ao2_container_count(channels);
04487       if (chan_count <= 1) {
04488          res = AST_BRIDGE_TRANSFER_INVALID;
04489          goto end;
04490       }
04491       transfer_prohibited = ast_test_flag(&the_bridge->feature_flags,
04492             AST_BRIDGE_FLAG_TRANSFER_PROHIBITED);
04493       do_bridge_transfer = ast_test_flag(&the_bridge->feature_flags,
04494             AST_BRIDGE_FLAG_TRANSFER_BRIDGE_ONLY) ||
04495             chan_count > 2;
04496    }
04497 
04498    if (transfer_prohibited) {
04499       res = AST_BRIDGE_TRANSFER_NOT_PERMITTED;
04500       goto end;
04501    }
04502 
04503    set_transfer_variables_all(to_transferee, channels, 1);
04504 
04505    if (do_bridge_transfer) {
04506       ast_bridge_lock(the_bridge);
04507       res = attended_transfer_bridge(chan_bridged, chan_unbridged, the_bridge, NULL, transfer_msg);
04508       ast_bridge_unlock(the_bridge);
04509       goto end;
04510    }
04511 
04512    transferee = get_transferee(channels, chan_bridged);
04513    if (!transferee) {
04514       res = AST_BRIDGE_TRANSFER_FAIL;
04515       goto end;
04516    }
04517 
04518    app = ast_strdupa(ast_channel_appl(chan_unbridged));
04519    if (bridge_channel_internal_queue_attended_transfer(transferee, chan_unbridged)) {
04520       res = AST_BRIDGE_TRANSFER_FAIL;
04521       goto end;
04522    }
04523 
04524    ast_bridge_remove(the_bridge, chan_bridged);
04525 
04526    ast_attended_transfer_message_add_app(transfer_msg, app, NULL);
04527    res = AST_BRIDGE_TRANSFER_SUCCESS;
04528 
04529 end:
04530    transfer_msg->result = res;
04531    ast_bridge_publish_attended_transfer(transfer_msg);
04532    return res;
04533 }
04534 
04535 /*!
04536  * \internal
04537  * \brief Service the bridge manager request.
04538  * \since 12.0.0
04539  *
04540  * \param bridge requesting service.
04541  *
04542  * \return Nothing
04543  */
04544 static void bridge_manager_service(struct ast_bridge *bridge)
04545 {
04546    ast_bridge_lock(bridge);
04547    if (bridge->callid) {
04548       ast_callid_threadassoc_change(bridge->callid);
04549    }
04550 
04551    /* Do any pending bridge actions. */
04552    bridge_handle_actions(bridge);
04553    ast_bridge_unlock(bridge);
04554 }
04555 
04556 /*!
04557  * \internal
04558  * \brief Bridge manager service thread.
04559  * \since 12.0.0
04560  *
04561  * \return Nothing
04562  */
04563 static void *bridge_manager_thread(void *data)
04564 {
04565    struct bridge_manager_controller *manager = data;
04566    struct bridge_manager_request *request;
04567 
04568    ao2_lock(manager);
04569    while (!manager->stop) {
04570       request = AST_LIST_REMOVE_HEAD(&manager->service_requests, node);
04571       if (!request) {
04572          ast_cond_wait(&manager->cond, ao2_object_get_lockaddr(manager));
04573          continue;
04574       }
04575       ao2_unlock(manager);
04576 
04577       /* Service the bridge. */
04578       bridge_manager_service(request->bridge);
04579       ao2_ref(request->bridge, -1);
04580       ast_free(request);
04581 
04582       ao2_lock(manager);
04583    }
04584    ao2_unlock(manager);
04585 
04586    return NULL;
04587 }
04588 
04589 /*!
04590  * \internal
04591  * \brief Destroy the bridge manager controller.
04592  * \since 12.0.0
04593  *
04594  * \param obj Bridge manager to destroy.
04595  *
04596  * \return Nothing
04597  */
04598 static void bridge_manager_destroy(void *obj)
04599 {
04600    struct bridge_manager_controller *manager = obj;
04601    struct bridge_manager_request *request;
04602 
04603    if (manager->thread != AST_PTHREADT_NULL) {
04604       /* Stop the manager thread. */
04605       ao2_lock(manager);
04606       manager->stop = 1;
04607       ast_cond_signal(&manager->cond);
04608       ao2_unlock(manager);
04609       ast_debug(1, "Waiting for bridge manager thread to die.\n");
04610       pthread_join(manager->thread, NULL);
04611    }
04612 
04613    /* Destroy the service request queue. */
04614    while ((request = AST_LIST_REMOVE_HEAD(&manager->service_requests, node))) {
04615       ao2_ref(request->bridge, -1);
04616       ast_free(request);
04617    }
04618 
04619    ast_cond_destroy(&manager->cond);
04620 }
04621 
04622 /*!
04623  * \internal
04624  * \brief Create the bridge manager controller.
04625  * \since 12.0.0
04626  *
04627  * \retval manager on success.
04628  * \retval NULL on error.
04629  */
04630 static struct bridge_manager_controller *bridge_manager_create(void)
04631 {
04632    struct bridge_manager_controller *manager;
04633 
04634    manager = ao2_alloc(sizeof(*manager), bridge_manager_destroy);
04635    if (!manager) {
04636       /* Well. This isn't good. */
04637       return NULL;
04638    }
04639    ast_cond_init(&manager->cond, NULL);
04640    AST_LIST_HEAD_INIT_NOLOCK(&manager->service_requests);
04641 
04642    /* Create the bridge manager thread. */
04643    if (ast_pthread_create(&manager->thread, NULL, bridge_manager_thread, manager)) {
04644       /* Well. This isn't good either. */
04645       manager->thread = AST_PTHREADT_NULL;
04646       ao2_ref(manager, -1);
04647       manager = NULL;
04648    }
04649 
04650    return manager;
04651 }
04652 
04653 /*!
04654  * \internal
04655  * \brief Bridge ao2 container sort function.
04656  * \since 12.0.0
04657  *
04658  * \param obj_left pointer to the (user-defined part) of an object.
04659  * \param obj_right pointer to the (user-defined part) of an object.
04660  * \param flags flags from ao2_callback()
04661  *   OBJ_POINTER - if set, 'obj_right', is an object.
04662  *   OBJ_KEY - if set, 'obj_right', is a search key item that is not an object.
04663  *   OBJ_PARTIAL_KEY - if set, 'obj_right', is a partial search key item that is not an object.
04664  *
04665  * \retval <0 if obj_left < obj_right
04666  * \retval =0 if obj_left == obj_right
04667  * \retval >0 if obj_left > obj_right
04668  */
04669 static int bridge_sort_cmp(const void *obj_left, const void *obj_right, int flags)
04670 {
04671    const struct ast_bridge *bridge_left = obj_left;
04672    const struct ast_bridge *bridge_right = obj_right;
04673    const char *right_key = obj_right;
04674    int cmp;
04675 
04676    switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
04677    default:
04678    case OBJ_POINTER:
04679       right_key = bridge_right->uniqueid;
04680       /* Fall through */
04681    case OBJ_KEY:
04682       cmp = strcmp(bridge_left->uniqueid, right_key);
04683       break;
04684    case OBJ_PARTIAL_KEY:
04685       cmp = strncmp(bridge_left->uniqueid, right_key, strlen(right_key));
04686       break;
04687    }
04688    return cmp;
04689 }
04690 
04691 struct ast_bridge *ast_bridge_find_by_id(const char *bridge_id)
04692 {
04693    return ao2_find(bridges, bridge_id, OBJ_SEARCH_KEY);
04694 }
04695 
04696 struct bridge_complete {
04697    /*! Nth match to return. */
04698    int state;
04699    /*! Which match currently on. */
04700    int which;
04701 };
04702 
04703 static int complete_bridge_live_search(void *obj, void *arg, void *data, int flags)
04704 {
04705    struct bridge_complete *search = data;
04706 
04707    if (++search->which > search->state) {
04708       return CMP_MATCH;
04709    }
04710    return 0;
04711 }
04712 
04713 static char *complete_bridge_live(const char *word, int state)
04714 {
04715    char *ret;
04716    struct ast_bridge *bridge;
04717    struct bridge_complete search = {
04718       .state = state,
04719       };
04720 
04721    bridge = ao2_callback_data(bridges, ast_strlen_zero(word) ? 0 : OBJ_PARTIAL_KEY,
04722       complete_bridge_live_search, (char *) word, &search);
04723    if (!bridge) {
04724       return NULL;
04725    }
04726    ret = ast_strdup(bridge->uniqueid);
04727    ao2_ref(bridge, -1);
04728    return ret;
04729 }
04730 
04731 static char *complete_bridge_stasis(const char *word, int state)
04732 {
04733    char *ret = NULL;
04734    int wordlen = strlen(word), which = 0;
04735    RAII_VAR(struct ao2_container *, cached_bridges, NULL, ao2_cleanup);
04736    struct ao2_iterator iter;
04737    struct stasis_message *msg;
04738 
04739    cached_bridges = stasis_cache_dump(ast_bridge_cache(), ast_bridge_snapshot_type());
04740    if (!cached_bridges) {
04741       return NULL;
04742    }
04743 
04744    iter = ao2_iterator_init(cached_bridges, 0);
04745    for (; (msg = ao2_iterator_next(&iter)); ao2_ref(msg, -1)) {
04746       struct ast_bridge_snapshot *snapshot = stasis_message_data(msg);
04747 
04748       if (!strncasecmp(word, snapshot->uniqueid, wordlen) && (++which > state)) {
04749          ret = ast_strdup(snapshot->uniqueid);
04750          ao2_ref(msg, -1);
04751          break;
04752       }
04753    }
04754    ao2_iterator_destroy(&iter);
04755 
04756    return ret;
04757 }
04758 
04759 static char *handle_bridge_show_all(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04760 {
04761 #define FORMAT_HDR "%-36s %5s %-15s %s\n"
04762 #define FORMAT_ROW "%-36s %5u %-15s %s\n"
04763 
04764    RAII_VAR(struct ao2_container *, cached_bridges, NULL, ao2_cleanup);
04765    struct ao2_iterator iter;
04766    struct stasis_message *msg;
04767 
04768    switch (cmd) {
04769    case CLI_INIT:
04770       e->command = "bridge show all";
04771       e->usage =
04772          "Usage: bridge show all\n"
04773          "       List all bridges\n";
04774       return NULL;
04775    case CLI_GENERATE:
04776       return NULL;
04777    }
04778 
04779    cached_bridges = stasis_cache_dump(ast_bridge_cache(), ast_bridge_snapshot_type());
04780    if (!cached_bridges) {
04781       ast_cli(a->fd, "Failed to retrieve cached bridges\n");
04782       return CLI_SUCCESS;
04783    }
04784 
04785    ast_cli(a->fd, FORMAT_HDR, "Bridge-ID", "Chans", "Type", "Technology");
04786 
04787    iter = ao2_iterator_init(cached_bridges, 0);
04788    for (; (msg = ao2_iterator_next(&iter)); ao2_ref(msg, -1)) {
04789       struct ast_bridge_snapshot *snapshot = stasis_message_data(msg);
04790 
04791       ast_cli(a->fd, FORMAT_ROW,
04792          snapshot->uniqueid,
04793          snapshot->num_channels,
04794          S_OR(snapshot->subclass, "<unknown>"),
04795          S_OR(snapshot->technology, "<unknown>"));
04796    }
04797    ao2_iterator_destroy(&iter);
04798    return CLI_SUCCESS;
04799 
04800 #undef FORMAT_HDR
04801 #undef FORMAT_ROW
04802 }
04803 
04804 /*! \brief Internal callback function for sending channels in a bridge to the CLI */
04805 static int bridge_show_specific_print_channel(void *obj, void *arg, int flags)
04806 {
04807    const char *uniqueid = obj;
04808    struct ast_cli_args *a = arg;
04809    RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
04810    struct ast_channel_snapshot *snapshot;
04811 
04812    msg = stasis_cache_get(ast_channel_cache(), ast_channel_snapshot_type(), uniqueid);
04813    if (!msg) {
04814       return 0;
04815    }
04816    snapshot = stasis_message_data(msg);
04817 
04818    ast_cli(a->fd, "Channel: %s\n", snapshot->name);
04819 
04820    return 0;
04821 }
04822 
04823 static char *handle_bridge_show_specific(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04824 {
04825    RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
04826    struct ast_bridge_snapshot *snapshot;
04827 
04828    switch (cmd) {
04829    case CLI_INIT:
04830       e->command = "bridge show";
04831       e->usage =
04832          "Usage: bridge show <bridge-id>\n"
04833          "       Show information about the <bridge-id> bridge\n";
04834       return NULL;
04835    case CLI_GENERATE:
04836       if (a->pos == 2) {
04837          return complete_bridge_stasis(a->word, a->n);
04838       }
04839       return NULL;
04840    }
04841 
04842    if (a->argc != 3) {
04843       return CLI_SHOWUSAGE;
04844    }
04845 
04846    msg = stasis_cache_get(ast_bridge_cache(), ast_bridge_snapshot_type(), a->argv[2]);
04847    if (!msg) {
04848       ast_cli(a->fd, "Bridge '%s' not found\n", a->argv[2]);
04849       return CLI_SUCCESS;
04850    }
04851 
04852    snapshot = stasis_message_data(msg);
04853    ast_cli(a->fd, "Id: %s\n", snapshot->uniqueid);
04854    ast_cli(a->fd, "Type: %s\n", S_OR(snapshot->subclass, "<unknown>"));
04855    ast_cli(a->fd, "Technology: %s\n", S_OR(snapshot->technology, "<unknown>"));
04856    ast_cli(a->fd, "Num-Channels: %u\n", snapshot->num_channels);
04857    ao2_callback(snapshot->channels, OBJ_NODATA, bridge_show_specific_print_channel, a);
04858 
04859    return CLI_SUCCESS;
04860 }
04861 
04862 #ifdef AST_DEVMODE
04863 static char *handle_bridge_destroy_specific(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04864 {
04865    struct ast_bridge *bridge;
04866 
04867    switch (cmd) {
04868    case CLI_INIT:
04869       e->command = "bridge destroy";
04870       e->usage =
04871          "Usage: bridge destroy <bridge-id>\n"
04872          "       Destroy the <bridge-id> bridge\n";
04873       return NULL;
04874    case CLI_GENERATE:
04875       if (a->pos == 2) {
04876          return complete_bridge_live(a->word, a->n);
04877       }
04878       return NULL;
04879    }
04880 
04881    if (a->argc != 3) {
04882       return CLI_SHOWUSAGE;
04883    }
04884 
04885    bridge = ast_bridge_find_by_id(a->argv[2]);
04886    if (!bridge) {
04887       ast_cli(a->fd, "Bridge '%s' not found\n", a->argv[2]);
04888       return CLI_SUCCESS;
04889    }
04890 
04891    ast_cli(a->fd, "Destroying bridge '%s'\n", a->argv[2]);
04892    ast_bridge_destroy(bridge, 0);
04893 
04894    return CLI_SUCCESS;
04895 }
04896 #endif
04897 
04898 static char *complete_bridge_participant(const char *bridge_name, const char *line, const char *word, int pos, int state)
04899 {
04900    struct ast_bridge *bridge;
04901    struct ast_bridge_channel *bridge_channel;
04902    int which;
04903    int wordlen;
04904 
04905    bridge = ast_bridge_find_by_id(bridge_name);
04906    if (!bridge) {
04907       return NULL;
04908    }
04909 
04910    if (!state) {
04911       ao2_ref(bridge, -1);
04912       return ast_strdup("all");
04913    }
04914    state--;
04915 
04916    {
04917       SCOPED_LOCK(bridge_lock, bridge, ast_bridge_lock, ast_bridge_unlock);
04918 
04919       which = 0;
04920       wordlen = strlen(word);
04921       AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
04922          if (!strncasecmp(ast_channel_name(bridge_channel->chan), word, wordlen)
04923             && ++which > state) {
04924             ao2_ref(bridge, -1);
04925             return ast_strdup(ast_channel_name(bridge_channel->chan));
04926          }
04927       }
04928    }
04929 
04930    ao2_ref(bridge, -1);
04931 
04932    return NULL;
04933 }
04934 
04935 static char *handle_bridge_kick_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04936 {
04937    struct ast_bridge *bridge;
04938 
04939    switch (cmd) {
04940    case CLI_INIT:
04941       e->command = "bridge kick";
04942       e->usage =
04943          "Usage: bridge kick <bridge-id> <channel-name | all>\n"
04944          "       Kick the <channel-name> channel out of the <bridge-id> bridge\n"
04945          "       If all is specified as the channel name then all channels will be\n"
04946          "       kicked out of the bridge.\n";
04947       return NULL;
04948    case CLI_GENERATE:
04949       if (a->pos == 2) {
04950          return complete_bridge_live(a->word, a->n);
04951       }
04952       if (a->pos == 3) {
04953          return complete_bridge_participant(a->argv[2], a->line, a->word, a->pos, a->n);
04954       }
04955       return NULL;
04956    }
04957 
04958    if (a->argc != 4) {
04959       return CLI_SHOWUSAGE;
04960    }
04961 
04962    bridge = ast_bridge_find_by_id(a->argv[2]);
04963    if (!bridge) {
04964       ast_cli(a->fd, "Bridge '%s' not found\n", a->argv[2]);
04965       return CLI_SUCCESS;
04966    }
04967 
04968    if (!strcasecmp(a->argv[3], "all")) {
04969       struct ast_bridge_channel *bridge_channel;
04970 
04971       ast_cli(a->fd, "Kicking all channels from bridge '%s'\n", a->argv[2]);
04972 
04973       ast_bridge_lock(bridge);
04974       AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
04975          ast_bridge_channel_queue_callback(bridge_channel, 0, kick_it, NULL, 0);
04976       }
04977       ast_bridge_unlock(bridge);
04978    } else {
04979       struct ast_channel *chan;
04980 
04981       chan = ast_channel_get_by_name_prefix(a->argv[3], strlen(a->argv[3]));
04982       if (!chan) {
04983          ast_cli(a->fd, "Channel '%s' not found\n", a->argv[3]);
04984          ao2_ref(bridge, -1);
04985          return CLI_SUCCESS;
04986       }
04987 
04988       ast_cli(a->fd, "Kicking channel '%s' from bridge '%s'\n",
04989          ast_channel_name(chan), a->argv[2]);
04990       ast_bridge_kick(bridge, chan);
04991       ast_channel_unref(chan);
04992    }
04993 
04994    ao2_ref(bridge, -1);
04995    return CLI_SUCCESS;
04996 }
04997 
04998 /*! Bridge technology capabilities to string. */
04999 static const char *tech_capability2str(uint32_t capabilities)
05000 {
05001    const char *type;
05002 
05003    if (capabilities & AST_BRIDGE_CAPABILITY_HOLDING) {
05004       type = "Holding";
05005    } else if (capabilities & AST_BRIDGE_CAPABILITY_EARLY) {
05006       type = "Early";
05007    } else if (capabilities & AST_BRIDGE_CAPABILITY_NATIVE) {
05008       type = "Native";
05009    } else if (capabilities & AST_BRIDGE_CAPABILITY_1TO1MIX) {
05010       type = "1to1Mix";
05011    } else if (capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX) {
05012       type = "MultiMix";
05013    } else {
05014       type = "<Unknown>";
05015    }
05016    return type;
05017 }
05018 
05019 static char *handle_bridge_technology_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
05020 {
05021 #define FORMAT_HDR "%-20s %-20s %8s %s\n"
05022 #define FORMAT_ROW "%-20s %-20s %8u %s\n"
05023 
05024    struct ast_bridge_technology *cur;
05025 
05026    switch (cmd) {
05027    case CLI_INIT:
05028       e->command = "bridge technology show";
05029       e->usage =
05030          "Usage: bridge technology show\n"
05031          "       List registered bridge technologies\n";
05032       return NULL;
05033    case CLI_GENERATE:
05034       return NULL;
05035    }
05036 
05037    ast_cli(a->fd, FORMAT_HDR, "Name", "Type", "Priority", "Suspended");
05038    AST_RWLIST_RDLOCK(&bridge_technologies);
05039    AST_RWLIST_TRAVERSE(&bridge_technologies, cur, entry) {
05040       const char *type;
05041 
05042       /* Decode type for display */
05043       type = tech_capability2str(cur->capabilities);
05044 
05045       ast_cli(a->fd, FORMAT_ROW, cur->name, type, cur->preference,
05046          AST_CLI_YESNO(cur->suspended));
05047    }
05048    AST_RWLIST_UNLOCK(&bridge_technologies);
05049    return CLI_SUCCESS;
05050 
05051 #undef FORMAT
05052 }
05053 
05054 static char *complete_bridge_technology(const char *word, int state)
05055 {
05056    struct ast_bridge_technology *cur;
05057    char *res;
05058    int which;
05059    int wordlen;
05060 
05061    which = 0;
05062    wordlen = strlen(word);
05063    AST_RWLIST_RDLOCK(&bridge_technologies);
05064    AST_RWLIST_TRAVERSE(&bridge_technologies, cur, entry) {
05065       if (!strncasecmp(cur->name, word, wordlen) && ++which > state) {
05066          res = ast_strdup(cur->name);
05067          AST_RWLIST_UNLOCK(&bridge_technologies);
05068          return res;
05069       }
05070    }
05071    AST_RWLIST_UNLOCK(&bridge_technologies);
05072    return NULL;
05073 }
05074 
05075 static char *handle_bridge_technology_suspend(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
05076 {
05077    struct ast_bridge_technology *cur;
05078    int suspend;
05079    int successful;
05080 
05081    switch (cmd) {
05082    case CLI_INIT:
05083       e->command = "bridge technology {suspend|unsuspend}";
05084       e->usage =
05085          "Usage: bridge technology {suspend|unsuspend} <technology-name>\n"
05086          "       Suspend or unsuspend a bridge technology.\n";
05087       return NULL;
05088    case CLI_GENERATE:
05089       if (a->pos == 3) {
05090          return complete_bridge_technology(a->word, a->n);
05091       }
05092       return NULL;
05093    }
05094 
05095    if (a->argc != 4) {
05096       return CLI_SHOWUSAGE;
05097    }
05098 
05099    suspend = !strcasecmp(a->argv[2], "suspend");
05100    successful = 0;
05101    AST_RWLIST_WRLOCK(&bridge_technologies);
05102    AST_RWLIST_TRAVERSE(&bridge_technologies, cur, entry) {
05103       if (!strcasecmp(cur->name, a->argv[3])) {
05104          successful = 1;
05105          if (suspend) {
05106             ast_bridge_technology_suspend(cur);
05107          } else {
05108             ast_bridge_technology_unsuspend(cur);
05109          }
05110          break;
05111       }
05112    }
05113    AST_RWLIST_UNLOCK(&bridge_technologies);
05114 
05115    if (successful) {
05116       if (suspend) {
05117          ast_cli(a->fd, "Suspended bridge technology '%s'\n", a->argv[3]);
05118       } else {
05119          ast_cli(a->fd, "Unsuspended bridge technology '%s'\n", a->argv[3]);
05120       }
05121    } else {
05122       ast_cli(a->fd, "Bridge technology '%s' not found\n", a->argv[3]);
05123    }
05124 
05125    return CLI_SUCCESS;
05126 }
05127 
05128 static struct ast_cli_entry bridge_cli[] = {
05129    AST_CLI_DEFINE(handle_bridge_show_all, "List all bridges"),
05130    AST_CLI_DEFINE(handle_bridge_show_specific, "Show information about a bridge"),
05131 #ifdef AST_DEVMODE
05132    AST_CLI_DEFINE(handle_bridge_destroy_specific, "Destroy a bridge"),
05133 #endif
05134    AST_CLI_DEFINE(handle_bridge_kick_channel, "Kick a channel from a bridge"),
05135    AST_CLI_DEFINE(handle_bridge_technology_show, "List registered bridge technologies"),
05136    AST_CLI_DEFINE(handle_bridge_technology_suspend, "Suspend/unsuspend a bridge technology"),
05137 };
05138 
05139 
05140 static int handle_manager_bridge_tech_suspend(struct mansession *s, const struct message *m, int suspend)
05141 {
05142    const char *name = astman_get_header(m, "BridgeTechnology");
05143    struct ast_bridge_technology *cur;
05144    int successful = 0;
05145 
05146    if (ast_strlen_zero(name)) {
05147       astman_send_error(s, m, "BridgeTechnology must be provided");
05148       return 0;
05149    }
05150 
05151    AST_RWLIST_RDLOCK(&bridge_technologies);
05152    AST_RWLIST_TRAVERSE(&bridge_technologies, cur, entry) {
05153 
05154       if (!strcasecmp(cur->name, name)) {
05155          successful = 1;
05156          if (suspend) {
05157             ast_bridge_technology_suspend(cur);
05158          } else {
05159             ast_bridge_technology_unsuspend(cur);
05160          }
05161          break;
05162       }
05163    }
05164    AST_RWLIST_UNLOCK(&bridge_technologies);
05165    if (!successful) {
05166       astman_send_error(s, m, "BridgeTechnology not found");
05167       return 0;
05168    }
05169 
05170    astman_send_ack(s, m, (suspend ? "Suspended bridge technology" : "Unsuspended bridge technology"));
05171    return 0;
05172 }
05173 
05174 static int manager_bridge_tech_suspend(struct mansession *s, const struct message *m)
05175 {
05176    return handle_manager_bridge_tech_suspend(s, m, 1);
05177 }
05178 
05179 static int manager_bridge_tech_unsuspend(struct mansession *s, const struct message *m)
05180 {
05181    return handle_manager_bridge_tech_suspend(s, m, 0);
05182 }
05183 
05184 static int manager_bridge_tech_list(struct mansession *s, const struct message *m)
05185 {
05186    const char *id = astman_get_header(m, "ActionID");
05187    RAII_VAR(struct ast_str *, id_text, ast_str_create(128), ast_free);
05188    struct ast_bridge_technology *cur;
05189    int num_items = 0;
05190 
05191    if (!id_text) {
05192       astman_send_error(s, m, "Internal error");
05193       return -1;
05194    }
05195 
05196    if (!ast_strlen_zero(id)) {
05197       ast_str_set(&id_text, 0, "ActionID: %s\r\n", id);
05198    }
05199 
05200    astman_send_listack(s, m, "Bridge technology listing will follow", "start");
05201 
05202    AST_RWLIST_RDLOCK(&bridge_technologies);
05203    AST_RWLIST_TRAVERSE(&bridge_technologies, cur, entry) {
05204       const char *type;
05205 
05206       type = tech_capability2str(cur->capabilities);
05207 
05208       astman_append(s,
05209          "Event: BridgeTechnologyListItem\r\n"
05210          "BridgeTechnology: %s\r\n"
05211          "BridgeType: %s\r\n"
05212          "BridgePriority: %u\r\n"
05213          "BridgeSuspended: %s\r\n"
05214          "%s"
05215          "\r\n",
05216          cur->name, type, cur->preference, AST_YESNO(cur->suspended),
05217          ast_str_buffer(id_text));
05218       ++num_items;
05219    }
05220    AST_RWLIST_UNLOCK(&bridge_technologies);
05221 
05222    astman_send_list_complete_start(s, m, "BridgeTechnologyListComplete", num_items);
05223    astman_send_list_complete_end(s);
05224 
05225    return 0;
05226 }
05227 
05228 /*!
05229  * \internal
05230  * \brief Print bridge object key (name).
05231  * \since 12.0.0
05232  *
05233  * \param v_obj A pointer to the object we want the key printed.
05234  * \param where User data needed by prnt to determine where to put output.
05235  * \param prnt Print output callback function to use.
05236  *
05237  * \return Nothing
05238  */
05239 static void bridge_prnt_obj(void *v_obj, void *where, ao2_prnt_fn *prnt)
05240 {
05241    struct ast_bridge *bridge = v_obj;
05242 
05243    if (!bridge) {
05244       return;
05245    }
05246    prnt(where, "%s %s chans:%u",
05247       bridge->uniqueid, bridge->v_table->name, bridge->num_channels);
05248 }
05249 
05250 /*!
05251  * \internal
05252  * \brief Shutdown the bridging system.  Stuff to do on graceful shutdown.
05253  * \since 13.3.0
05254  *
05255  * \return Nothing
05256  */
05257 static void bridge_cleanup(void)
05258 {
05259    ast_manager_unregister("BridgeTechnologyList");
05260    ast_manager_unregister("BridgeTechnologySuspend");
05261    ast_manager_unregister("BridgeTechnologyUnsuspend");
05262    ast_cli_unregister_multiple(bridge_cli, ARRAY_LEN(bridge_cli));
05263    ao2_container_unregister("bridges");
05264 
05265    ao2_cleanup(bridges);
05266    bridges = NULL;
05267    ao2_cleanup(bridge_manager);
05268    bridge_manager = NULL;
05269 }
05270 
05271 int ast_bridging_init(void)
05272 {
05273    ast_register_cleanup(bridge_cleanup);
05274 
05275    if (ast_stasis_bridging_init()) {
05276       return -1;
05277    }
05278 
05279    bridge_manager = bridge_manager_create();
05280    if (!bridge_manager) {
05281       return -1;
05282    }
05283 
05284    bridges = ao2_container_alloc_rbtree(AO2_ALLOC_OPT_LOCK_MUTEX,
05285       AO2_CONTAINER_ALLOC_OPT_DUPS_REPLACE, bridge_sort_cmp, NULL);
05286    if (!bridges) {
05287       return -1;
05288    }
05289    ao2_container_register("bridges", bridges, bridge_prnt_obj);
05290 
05291    ast_bridging_init_basic();
05292 
05293    ast_cli_register_multiple(bridge_cli, ARRAY_LEN(bridge_cli));
05294 
05295    ast_manager_register_xml_core("BridgeTechnologyList", 0, manager_bridge_tech_list);
05296    ast_manager_register_xml_core("BridgeTechnologySuspend", 0, manager_bridge_tech_suspend);
05297    ast_manager_register_xml_core("BridgeTechnologyUnsuspend", 0, manager_bridge_tech_unsuspend);
05298 
05299    return 0;
05300 }

Generated on Thu Apr 16 06:27:15 2015 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.6