Sat Mar 26 11:07:35 2011

Asterisk developer's documentation


features.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2008, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@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 Routines implementing call features as call pickup, parking and transfer
00022  *
00023  * \author Mark Spencer <markster@digium.com> 
00024  */
00025 
00026 #include "asterisk.h"
00027 
00028 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 289340 $")
00029 
00030 #include "asterisk/_private.h"
00031 
00032 #include <pthread.h>
00033 #include <signal.h>
00034 #include <sys/time.h>
00035 #include <sys/signal.h>
00036 #include <netinet/in.h>
00037 
00038 #include "asterisk/lock.h"
00039 #include "asterisk/file.h"
00040 #include "asterisk/channel.h"
00041 #include "asterisk/pbx.h"
00042 #include "asterisk/causes.h"
00043 #include "asterisk/module.h"
00044 #include "asterisk/translate.h"
00045 #include "asterisk/app.h"
00046 #include "asterisk/say.h"
00047 #include "asterisk/features.h"
00048 #include "asterisk/musiconhold.h"
00049 #include "asterisk/config.h"
00050 #include "asterisk/cli.h"
00051 #include "asterisk/manager.h"
00052 #include "asterisk/utils.h"
00053 #include "asterisk/adsi.h"
00054 #include "asterisk/devicestate.h"
00055 #include "asterisk/monitor.h"
00056 #include "asterisk/audiohook.h"
00057 #include "asterisk/global_datastores.h"
00058 #include "asterisk/astobj2.h"
00059 #include "asterisk/cel.h"
00060 #include "asterisk/test.h"
00061 
00062 /*** DOCUMENTATION
00063    <application name="Bridge" language="en_US">
00064       <synopsis>
00065          Bridge two channels.
00066       </synopsis>
00067       <syntax>
00068          <parameter name="channel" required="true">
00069             <para>The current channel is bridged to the specified <replaceable>channel</replaceable>.</para>
00070          </parameter>
00071          <parameter name="options">
00072             <optionlist>
00073                <option name="p">
00074                   <para>Play a courtesy tone to <replaceable>channel</replaceable>.</para>
00075                </option>
00076                <option name="h">
00077                   <para>Allow the called party to hang up by sending the
00078                   <replaceable>*</replaceable> DTMF digit.</para>
00079                </option>
00080                <option name="H">
00081                   <para>Allow the calling party to hang up by pressing the
00082                   <replaceable>*</replaceable> DTMF digit.</para>
00083                </option>
00084                <option name="k">
00085                   <para>Allow the called party to enable parking of the call by sending
00086                   the DTMF sequence defined for call parking in features.conf.</para>
00087                </option>
00088                <option name="K">
00089                   <para>Allow the calling party to enable parking of the call by sending
00090                    the DTMF sequence defined for call parking in features.conf.</para>
00091                </option>
00092                <option name="L(x[:y][:z])">
00093                   <para>Limit the call to <replaceable>x</replaceable> ms. Play a warning
00094                   when <replaceable>y</replaceable> ms are left. Repeat the warning every
00095                   <replaceable>z</replaceable> ms. The following special variables can be
00096                   used with this option:</para>
00097                   <variablelist>
00098                      <variable name="LIMIT_PLAYAUDIO_CALLER">
00099                         <para>Play sounds to the caller. yes|no (default yes)</para>
00100                      </variable>
00101                      <variable name="LIMIT_PLAYAUDIO_CALLEE">   
00102                         <para>Play sounds to the callee. yes|no</para>
00103                      </variable>
00104                      <variable name="LIMIT_TIMEOUT_FILE">
00105                         <para>File to play when time is up.</para>
00106                      </variable>
00107                      <variable name="LIMIT_CONNECT_FILE">
00108                         <para>File to play when call begins.</para>
00109                      </variable>
00110                      <variable name="LIMIT_WARNING_FILE">
00111                         <para>File to play as warning if <replaceable>y</replaceable> is
00112                         defined. The default is to say the time remaining.</para>
00113                      </variable>
00114                   </variablelist>
00115                </option>
00116                <option name="S(x)">
00117                   <para>Hang up the call after <replaceable>x</replaceable> seconds *after* the called party has answered the call.</para>
00118                </option>
00119                <option name="t">
00120                   <para>Allow the called party to transfer the calling party by sending the
00121                   DTMF sequence defined in features.conf.</para>
00122                </option>
00123                <option name="T">
00124                   <para>Allow the calling party to transfer the called party by sending the
00125                   DTMF sequence defined in features.conf.</para>
00126                </option>
00127                <option name="w">
00128                   <para>Allow the called party to enable recording of the call by sending
00129                   the DTMF sequence defined for one-touch recording in features.conf.</para>
00130                </option>
00131                <option name="W">
00132                   <para>Allow the calling party to enable recording of the call by sending
00133                   the DTMF sequence defined for one-touch recording in features.conf.</para>
00134                </option>
00135                <option name="x">
00136                   <para>Cause the called party to be hung up after the bridge, instead of being
00137                   restarted in the dialplan.</para>
00138                </option>
00139             </optionlist>
00140          </parameter>
00141       </syntax>
00142       <description>
00143          <para>Allows the ability to bridge two channels via the dialplan.</para>
00144          <para>This application sets the following channel variable upon completion:</para>
00145          <variablelist>
00146             <variable name="BRIDGERESULT">
00147                <para>The result of the bridge attempt as a text string.</para>
00148                <value name="SUCCESS" />
00149                <value name="FAILURE" />
00150                <value name="LOOP" />
00151                <value name="NONEXISTENT" />
00152                <value name="INCOMPATIBLE" />
00153             </variable>
00154          </variablelist>
00155       </description>
00156    </application>
00157    <application name="ParkedCall" language="en_US">
00158       <synopsis>
00159          Answer a parked call.
00160       </synopsis>
00161       <syntax>
00162          <parameter name="exten" required="true" />
00163       </syntax>
00164       <description>
00165          <para>Used to connect to a parked call. This application is always
00166          registered internally and does not need to be explicitly added
00167          into the dialplan, although you should include the <literal>parkedcalls</literal>
00168          context. If no extension is provided, then the first available
00169          parked call will be acquired.</para>
00170       </description>
00171       <see-also>
00172          <ref type="application">Park</ref>
00173          <ref type="application">ParkAndAnnounce</ref>
00174       </see-also>
00175    </application>
00176    <application name="Park" language="en_US">
00177       <synopsis>
00178          Park yourself.
00179       </synopsis>
00180       <syntax>
00181          <parameter name="timeout">
00182             <para>A custom parking timeout for this parked call.</para>
00183          </parameter>
00184          <parameter name="return_context">
00185             <para>The context to return the call to after it times out.</para>
00186          </parameter>
00187          <parameter name="return_exten">
00188             <para>The extension to return the call to after it times out.</para>
00189          </parameter>
00190          <parameter name="return_priority">
00191             <para>The priority to return the call to after it times out.</para>
00192          </parameter>
00193          <parameter name="options">
00194             <para>A list of options for this parked call.</para>
00195             <optionlist>
00196                <option name="r">
00197                   <para>Send ringing instead of MOH to the parked call.</para>
00198                </option>
00199                <option name="R">
00200                   <para>Randomize the selection of a parking space.</para>
00201                </option>
00202                <option name="s">
00203                   <para>Silence announcement of the parking space number.</para>
00204                </option>
00205             </optionlist>
00206          </parameter>
00207       </syntax>
00208       <description>
00209          <para>Used to park yourself (typically in combination with a supervised
00210          transfer to know the parking space). This application is always
00211          registered internally and does not need to be explicitly added
00212          into the dialplan, although you should include the <literal>parkedcalls</literal>
00213          context (or the context specified in <filename>features.conf</filename>).</para>
00214          <para>If you set the <variable>PARKINGLOT</variable> variable, the call will be parked
00215          in the specifed parking context. Note setting this variable overrides the <variable>
00216          PARKINGLOT</variable> set by the <literal>CHANNEL</literal> function.</para>
00217          <para>If you set the <variable>PARKINGEXTEN</variable> variable to an extension in your
00218          parking context, Park() will park the call on that extension, unless
00219          it already exists. In that case, execution will continue at next priority.</para>
00220          <para>If you set the <variable>PARKINGLOT</variable> variable, Park() will park the call
00221          in that parkinglot.</para>
00222          <para>If you set the <variable>PARKINGDYNAMIC</variable> variable, this parkinglot from features.conf
00223          will be used as template for the newly created dynamic lot.</para>
00224          <para>If you set the <variable>PARKINGDYNCONTEXT</variable> variable the newly created dynamic
00225          parking lot will use this context.</para>
00226          <para>If you set the <variable>PARKINGDYNPOS</variable> variable the newly created dynamic parkinglot
00227          will use those parking postitions.</para>
00228       </description>
00229       <see-also>
00230          <ref type="application">ParkAndAnnounce</ref>
00231          <ref type="application">ParkedCall</ref>
00232       </see-also>
00233    </application>
00234    <manager name="ParkedCalls" language="en_US">
00235       <synopsis>
00236          List parked calls.
00237       </synopsis>
00238       <syntax>
00239          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00240       </syntax>
00241       <description>
00242          <para>List parked calls.</para>
00243       </description>
00244    </manager>
00245    <manager name="Park" language="en_US">
00246       <synopsis>
00247          Park a channel.
00248       </synopsis>
00249       <syntax>
00250          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00251          <parameter name="Channel" required="true">
00252             <para>Channel name to park.</para>
00253          </parameter>
00254          <parameter name="Channel2" required="true">
00255             <para>Channel to announce park info to (and return to if timeout).</para>
00256          </parameter>
00257          <parameter name="Timeout">
00258             <para>Number of milliseconds to wait before callback.</para>
00259          </parameter>
00260          <parameter name="Parkinglot">
00261             <para>Parking lot to park channel in.</para>
00262          </parameter>
00263       </syntax>
00264       <description>
00265          <para>Park a channel.</para>
00266       </description>
00267    </manager>
00268    <manager name="Bridge" language="en_US">
00269       <synopsis>
00270          Bridge two channels already in the PBX.
00271       </synopsis>
00272       <syntax>
00273          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00274          <parameter name="Channel1" required="true">
00275             <para>Channel to Bridge to Channel2.</para>
00276          </parameter>
00277          <parameter name="Channel2" required="true">
00278             <para>Channel to Bridge to Channel1.</para>
00279          </parameter>
00280          <parameter name="Tone">
00281             <para>Play courtesy tone to Channel 2.</para>
00282             <enumlist>
00283                <enum name="yes" />
00284                <enum name="no" />
00285             </enumlist>
00286          </parameter>
00287       </syntax>
00288       <description>
00289          <para>Bridge together two channels already in the PBX.</para>
00290       </description>
00291    </manager>
00292  ***/
00293 
00294 #define DEFAULT_PARK_TIME 45000
00295 #define DEFAULT_PARK_EXTENSION "700"
00296 #define DEFAULT_TRANSFER_DIGIT_TIMEOUT 3000
00297 #define DEFAULT_FEATURE_DIGIT_TIMEOUT 1000
00298 #define DEFAULT_NOANSWER_TIMEOUT_ATTENDED_TRANSFER 15000
00299 #define DEFAULT_ATXFER_DROP_CALL 0
00300 #define DEFAULT_ATXFER_LOOP_DELAY 10000
00301 #define DEFAULT_ATXFER_CALLBACK_RETRIES 2
00302 
00303 #define AST_MAX_WATCHERS 256
00304 #define MAX_DIAL_FEATURE_OPTIONS 30
00305 
00306 struct feature_group_exten {
00307    AST_LIST_ENTRY(feature_group_exten) entry;
00308    AST_DECLARE_STRING_FIELDS(
00309       AST_STRING_FIELD(exten);
00310    );
00311    struct ast_call_feature *feature;
00312 };
00313 
00314 struct feature_group {
00315    AST_LIST_ENTRY(feature_group) entry;
00316    AST_DECLARE_STRING_FIELDS(
00317       AST_STRING_FIELD(gname);
00318    );
00319    AST_LIST_HEAD_NOLOCK(, feature_group_exten) features;
00320 };
00321 
00322 static AST_RWLIST_HEAD_STATIC(feature_groups, feature_group);
00323 
00324 static char *parkedcall = "ParkedCall";
00325 
00326 static char pickup_ext[AST_MAX_EXTENSION];                 /*!< Call pickup extension */
00327 
00328 /*! \brief Description of one parked call, added to a list while active, then removed.
00329    The list belongs to a parkinglot 
00330 */
00331 struct parkeduser {
00332    struct ast_channel *chan;                   /*!< Parking channel */
00333    struct timeval start;                       /*!< Time the parking started */
00334    int parkingnum;                             /*!< Parking lot */
00335    char parkingexten[AST_MAX_EXTENSION];       /*!< If set beforehand, parking extension used for this call */
00336    char context[AST_MAX_CONTEXT];              /*!< Where to go if our parking time expires */
00337    char exten[AST_MAX_EXTENSION];
00338    int priority;
00339    int parkingtime;                            /*!< Maximum length in parking lot before return */
00340    unsigned int notquiteyet:1;
00341    unsigned int options_specified:1;
00342    char peername[1024];
00343    unsigned char moh_trys;
00344    struct ast_parkinglot *parkinglot;
00345    AST_LIST_ENTRY(parkeduser) list;
00346 };
00347 
00348 /*! \brief Structure for parking lots which are put in a container. */
00349 struct ast_parkinglot {
00350    char name[AST_MAX_CONTEXT];
00351    char parkext[AST_MAX_EXTENSION];          /*!< Parkingextension */
00352    char parking_con[AST_MAX_EXTENSION];      /*!< Context for which parking is made accessible */
00353    char parking_con_dial[AST_MAX_EXTENSION]; /*!< Context for dialback for parking (KLUDGE) */
00354    int parking_start;            /*!< First available extension for parking */
00355    int parking_stop;          /*!< Last available extension for parking */
00356    int parking_offset;
00357    int parkfindnext;
00358    int parkingtime;           /*!< Default parking time */
00359    char mohclass[MAX_MUSICCLASS];                  /*!< Music class used for parking */
00360    int parkaddhints;                               /*!< Add parking hints automatically */
00361    int parkedcalltransfers;                        /*!< Enable DTMF based transfers on bridge when picking up parked calls */
00362    int parkedcallreparking;                        /*!< Enable DTMF based parking on bridge when picking up parked calls */
00363    int parkedcallhangup;                           /*!< Enable DTMF based hangup on a bridge when pickup up parked calls */
00364    int parkedcallrecording;                        /*!< Enable DTMF based recording on a bridge when picking up parked calls */
00365    unsigned short the_mark:1;                      /*!< Used during reloads, that which bears the_mark shall be deleted! */
00366    AST_LIST_HEAD(parkinglot_parklist, parkeduser) parkings; /*!< List of active parkings in this parkinglot */
00367 };
00368 
00369 /*! \brief The list of parking lots configured. Always at least one  - the default parking lot */
00370 static struct ao2_container *parkinglots;
00371  
00372 struct ast_parkinglot *default_parkinglot;
00373 char parking_ext[AST_MAX_EXTENSION];            /*!< Extension you type to park the call */
00374 
00375 static char courtesytone[256];                             /*!< Courtesy tone */
00376 static int parkedplay = 0;                                 /*!< Who to play the courtesy tone to */
00377 static int parkeddynamic = 0;                              /*!< Enable creation of parkinglots dynamically */
00378 static char xfersound[256];                                /*!< Call transfer sound */
00379 static char xferfailsound[256];                            /*!< Call transfer failure sound */
00380 static char pickupsound[256];                              /*!< Pickup sound */
00381 static char pickupfailsound[256];                          /*!< Pickup failure sound */
00382 
00383 static int adsipark;
00384 
00385 static int transferdigittimeout;
00386 static int featuredigittimeout;
00387 static int comebacktoorigin = 1;
00388 
00389 static int atxfernoanswertimeout;
00390 static unsigned int atxferdropcall;
00391 static unsigned int atxferloopdelay;
00392 static unsigned int atxfercallbackretries;
00393 
00394 static char *registrar = "features";         /*!< Registrar for operations */
00395 
00396 /* module and CLI command definitions */
00397 static char *parkcall = PARK_APP_NAME;
00398 
00399 static struct ast_app *monitor_app = NULL;
00400 static int monitor_ok = 1;
00401 
00402 static struct ast_app *mixmonitor_app = NULL;
00403 static int mixmonitor_ok = 1;
00404 
00405 static struct ast_app *stopmixmonitor_app = NULL;
00406 static int stopmixmonitor_ok = 1;
00407 
00408 static pthread_t parking_thread;
00409 struct ast_dial_features {
00410    struct ast_flags features_caller;
00411    struct ast_flags features_callee;
00412    int is_caller;
00413 };
00414 
00415 static void *dial_features_duplicate(void *data)
00416 {
00417    struct ast_dial_features *df = data, *df_copy;
00418  
00419    if (!(df_copy = ast_calloc(1, sizeof(*df)))) {
00420       return NULL;
00421    }
00422  
00423    memcpy(df_copy, df, sizeof(*df));
00424  
00425    return df_copy;
00426 }
00427 
00428 static void dial_features_destroy(void *data)
00429 {
00430    struct ast_dial_features *df = data;
00431    if (df) {
00432       ast_free(df);
00433    }
00434 }
00435 
00436 static const struct ast_datastore_info dial_features_info = {
00437    .type = "dial-features",
00438    .destroy = dial_features_destroy,
00439    .duplicate = dial_features_duplicate,
00440  };
00441  
00442 /* Forward declarations */
00443 static struct ast_parkinglot *parkinglot_addref(struct ast_parkinglot *parkinglot);
00444 static void parkinglot_unref(struct ast_parkinglot *parkinglot);
00445 static void parkinglot_destroy(void *obj);
00446 int manage_parkinglot(struct ast_parkinglot *curlot, const struct pollfd *pfds, const int nfds, struct pollfd **new_pfds, int *new_nfds, int *fs);
00447 struct ast_parkinglot *find_parkinglot(const char *name);
00448 static struct ast_parkinglot *create_parkinglot(const char *name);
00449 static struct ast_parkinglot *copy_parkinglot(const char *name, const struct ast_parkinglot *parkinglot);
00450 
00451 static int find_parkinglot_by_position_cb(void *obj, void *args, int flags)
00452 {
00453    struct ast_parkinglot *parkinglot = obj;
00454    int *parkpos = args;
00455 
00456    if (*parkpos >= parkinglot->parking_start && *parkpos <= parkinglot->parking_stop) {
00457       return CMP_MATCH | CMP_STOP;
00458    }
00459 
00460    return 0;
00461 }
00462 
00463 static int find_parkinglot_by_exten_cb(void *obj, void *args, int flags)
00464 {
00465    struct ast_parkinglot *parkinglot = obj;
00466    const char *parkext = args;
00467 
00468    if (!strcmp(parkinglot->parkext, parkext)) {
00469       return CMP_MATCH | CMP_STOP;
00470    }
00471 
00472    return 0;
00473 }
00474 
00475 int ast_parking_ext_valid(const char *exten_str, struct ast_channel *chan, const char *context)
00476 {
00477    struct ast_exten *exten;
00478    struct pbx_find_info q = { .stacklen = 0 }; /* the rest is reset in pbx_find_extension */
00479    const char *app_at_exten;
00480 
00481    exten = pbx_find_extension(chan, NULL, &q, context, exten_str, 1, NULL, NULL, E_MATCH);
00482    if (!exten) {
00483       return 0;
00484    }
00485 
00486    app_at_exten = ast_get_extension_app(exten);
00487    if (!app_at_exten || strcmp(PARK_APP_NAME, app_at_exten)) {
00488       return 0;
00489    }
00490 
00491    return 1;
00492 }
00493 
00494 const char *ast_pickup_ext(void)
00495 {
00496    return pickup_ext;
00497 }
00498 
00499 struct ast_bridge_thread_obj 
00500 {
00501    struct ast_bridge_config bconfig;
00502    struct ast_channel *chan;
00503    struct ast_channel *peer;
00504    unsigned int return_to_pbx:1;
00505 };
00506 
00507 static int parkinglot_hash_cb(const void *obj, const int flags)
00508 {
00509    const struct ast_parkinglot *parkinglot = obj;
00510 
00511    return ast_str_case_hash(parkinglot->name);
00512 }
00513 
00514 static int parkinglot_cmp_cb(void *obj, void *arg, int flags)
00515 {
00516    struct ast_parkinglot *parkinglot = obj, *parkinglot2 = arg;
00517 
00518    return !strcasecmp(parkinglot->name, parkinglot2->name) ? CMP_MATCH | CMP_STOP : 0;
00519 }
00520 
00521 /*!
00522  * \brief store context, extension and priority 
00523  * \param chan, context, ext, pri
00524 */
00525 static void set_c_e_p(struct ast_channel *chan, const char *context, const char *ext, int pri)
00526 {
00527    ast_copy_string(chan->context, context, sizeof(chan->context));
00528    ast_copy_string(chan->exten, ext, sizeof(chan->exten));
00529    chan->priority = pri;
00530 }
00531 
00532 /*!
00533  * \brief Check goto on transfer
00534  * \param chan
00535  *
00536  * Check if channel has 'GOTO_ON_BLINDXFR' set, if not exit.
00537  * When found make sure the types are compatible. Check if channel is valid
00538  * if so start the new channel else hangup the call. 
00539 */
00540 static void check_goto_on_transfer(struct ast_channel *chan) 
00541 {
00542    struct ast_channel *xferchan;
00543    const char *val = pbx_builtin_getvar_helper(chan, "GOTO_ON_BLINDXFR");
00544    char *x, *goto_on_transfer;
00545    struct ast_frame *f;
00546 
00547    if (ast_strlen_zero(val))
00548       return;
00549 
00550    goto_on_transfer = ast_strdupa(val);
00551 
00552    if (!(xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", chan->linkedid, 0, "%s", chan->name)))
00553       return;
00554 
00555    for (x = goto_on_transfer; x && *x; x++) {
00556       if (*x == '^')
00557          *x = '|';
00558    }
00559    /* Make formats okay */
00560    xferchan->readformat = chan->readformat;
00561    xferchan->writeformat = chan->writeformat;
00562    ast_channel_masquerade(xferchan, chan);
00563    ast_parseable_goto(xferchan, goto_on_transfer);
00564    xferchan->_state = AST_STATE_UP;
00565    ast_clear_flag(xferchan, AST_FLAGS_ALL);  
00566    xferchan->_softhangup = 0;
00567    if ((f = ast_read(xferchan))) {
00568       ast_frfree(f);
00569       f = NULL;
00570       ast_pbx_start(xferchan);
00571    } else {
00572       ast_hangup(xferchan);
00573    }
00574 }
00575 
00576 static struct ast_channel *feature_request_and_dial(struct ast_channel *caller, struct ast_channel *transferee, const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name, int igncallerstate, const char *language);
00577 
00578 /*!
00579  * \brief bridge the call 
00580  * \param data thread bridge.
00581  *
00582  * Set Last Data for respective channels, reset cdr for channels
00583  * bridge call, check if we're going back to dialplan
00584  * if not hangup both legs of the call
00585 */
00586 static void *bridge_call_thread(void *data)
00587 {
00588    struct ast_bridge_thread_obj *tobj = data;
00589    int res;
00590 
00591    tobj->chan->appl = !tobj->return_to_pbx ? "Transferred Call" : "ManagerBridge";
00592    tobj->chan->data = tobj->peer->name;
00593    tobj->peer->appl = !tobj->return_to_pbx ? "Transferred Call" : "ManagerBridge";
00594    tobj->peer->data = tobj->chan->name;
00595 
00596    ast_bridge_call(tobj->peer, tobj->chan, &tobj->bconfig);
00597 
00598    if (tobj->return_to_pbx) {
00599       if (!ast_check_hangup(tobj->peer)) {
00600          ast_log(LOG_VERBOSE, "putting peer %s into PBX again\n", tobj->peer->name);
00601          res = ast_pbx_start(tobj->peer);
00602          if (res != AST_PBX_SUCCESS)
00603             ast_log(LOG_WARNING, "FAILED continuing PBX on peer %s\n", tobj->peer->name);
00604       } else
00605          ast_hangup(tobj->peer);
00606       if (!ast_check_hangup(tobj->chan)) {
00607          ast_log(LOG_VERBOSE, "putting chan %s into PBX again\n", tobj->chan->name);
00608          res = ast_pbx_start(tobj->chan);
00609          if (res != AST_PBX_SUCCESS)
00610             ast_log(LOG_WARNING, "FAILED continuing PBX on chan %s\n", tobj->chan->name);
00611       } else
00612          ast_hangup(tobj->chan);
00613    } else {
00614       ast_hangup(tobj->chan);
00615       ast_hangup(tobj->peer);
00616    }
00617 
00618    ast_free(tobj);
00619 
00620    return NULL;
00621 }
00622 
00623 /*!
00624  * \brief create thread for the parked call
00625  * \param data
00626  *
00627  * Create thread and attributes, call bridge_call_thread
00628 */
00629 static void bridge_call_thread_launch(void *data) 
00630 {
00631    pthread_t thread;
00632    pthread_attr_t attr;
00633    struct sched_param sched;
00634 
00635    pthread_attr_init(&attr);
00636    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
00637    ast_pthread_create(&thread, &attr, bridge_call_thread, data);
00638    pthread_attr_destroy(&attr);
00639    memset(&sched, 0, sizeof(sched));
00640    pthread_setschedparam(thread, SCHED_RR, &sched);
00641 }
00642 
00643 /*!
00644  * \brief Announce call parking by ADSI
00645  * \param chan .
00646  * \param parkingexten .
00647  * Create message to show for ADSI, display message.
00648  * \retval 0 on success.
00649  * \retval -1 on failure.
00650 */
00651 static int adsi_announce_park(struct ast_channel *chan, char *parkingexten)
00652 {
00653    int res;
00654    int justify[5] = {ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT};
00655    char tmp[256];
00656    char *message[5] = {NULL, NULL, NULL, NULL, NULL};
00657 
00658    snprintf(tmp, sizeof(tmp), "Parked on %s", parkingexten);
00659    message[0] = tmp;
00660    res = ast_adsi_load_session(chan, NULL, 0, 1);
00661    if (res == -1)
00662       return res;
00663    return ast_adsi_print(chan, message, justify, 1);
00664 }
00665 
00666 /*! \brief Find parking lot name from channel */
00667 static const char *findparkinglotname(struct ast_channel *chan)
00668 {
00669    const char *temp, *parkinglot = NULL;
00670 
00671    /* Check if the channel has a parking lot */
00672    if (!ast_strlen_zero(chan->parkinglot))
00673       parkinglot = chan->parkinglot;
00674 
00675    /* Channel variables override everything */
00676 
00677    if ((temp  = pbx_builtin_getvar_helper(chan, "PARKINGLOT")))
00678       return temp;
00679 
00680    return parkinglot;
00681 }
00682 
00683 /*! \brief Notify metermaids that we've changed an extension */
00684 static void notify_metermaids(const char *exten, char *context, enum ast_device_state state)
00685 {
00686    ast_debug(4, "Notification of state change to metermaids %s@%s\n to state '%s'", 
00687       exten, context, ast_devstate2str(state));
00688 
00689    ast_devstate_changed(state, "park:%s@%s", exten, context);
00690 }
00691 
00692 /*! \brief metermaids callback from devicestate.c */
00693 static enum ast_device_state metermaidstate(const char *data)
00694 {
00695    char *context;
00696    char *exten;
00697 
00698    context = ast_strdupa(data);
00699 
00700    exten = strsep(&context, "@");
00701    if (!context)
00702       return AST_DEVICE_INVALID;
00703    
00704    ast_debug(4, "Checking state of exten %s in context %s\n", exten, context);
00705 
00706    if (!ast_exists_extension(NULL, context, exten, 1, NULL))
00707       return AST_DEVICE_NOT_INUSE;
00708 
00709    return AST_DEVICE_INUSE;
00710 }
00711 
00712 /*! Options to pass to park_call_full */
00713 enum ast_park_call_options {
00714    /*! Provide ringing to the parked caller instead of music on hold */
00715    AST_PARK_OPT_RINGING =   (1 << 0),
00716    /*! Randomly choose a parking spot for the caller instead of choosing
00717     *  the first one that is available. */
00718    AST_PARK_OPT_RANDOMIZE = (1 << 1),
00719    /*! Do not announce the parking number */
00720    AST_PARK_OPT_SILENCE = (1 << 2),
00721 };
00722 
00723 struct ast_park_call_args {
00724    /*! How long to wait in the parking lot before the call gets sent back
00725     *  to the specified return extension (or a best guess at where it came
00726     *  from if not explicitly specified). */
00727    int timeout;
00728    /*! An output parameter to store the parking space where the parked caller
00729     *  was placed. */
00730    int *extout;
00731    const char *orig_chan_name;
00732    const char *return_con;
00733    const char *return_ext;
00734    int return_pri;
00735    uint32_t flags;
00736    /*! Parked user that has already obtained a parking space */
00737    struct parkeduser *pu;
00738    struct ast_parkinglot *parkinglot; /*! parkinglot to be parked in, based on parkext */
00739 };
00740 
00741 static struct parkeduser *park_space_reserve(struct ast_channel *chan, struct ast_channel *peer, struct ast_park_call_args *args)
00742 {
00743    struct parkeduser *pu;
00744    int i, parking_space = -1, parking_range;
00745    const char *parkinglotname = NULL;
00746    const char *parkingexten;
00747    struct ast_parkinglot *parkinglot = NULL;
00748 
00749    if (args->parkinglot) {
00750       parkinglot = args->parkinglot;
00751       parkinglotname = parkinglot->name;
00752    } else if (peer) {
00753       parkinglotname = findparkinglotname(peer);
00754    } else { /* peer was NULL, check chan (ParkAndAnnounce / res_agi) */
00755       parkinglotname = findparkinglotname(chan);
00756    }
00757 
00758    if (!args->parkinglot) {
00759       if (parkinglotname) {
00760          parkinglot = find_parkinglot(parkinglotname);
00761       } else {
00762          ast_debug(4, "This could be an indication channel driver needs updating, using default lot.\n");
00763          parkinglot = parkinglot_addref(default_parkinglot);
00764       }
00765       ast_debug(1, "Found chanvar Parkinglot: %s\n", parkinglot->name);
00766    }
00767 
00768    /* Dynamically create parkinglot */
00769    if (!parkinglot && parkeddynamic && !ast_strlen_zero(parkinglotname)) {
00770       const char *dyn_context, *dyn_range;
00771       const char *parkinglotname_copy = NULL;
00772       struct ast_parkinglot *parkinglot_copy = NULL;
00773       int dyn_start, dyn_end;
00774 
00775       ast_channel_lock(chan);
00776       parkinglotname_copy = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNAMIC"), ""));
00777       dyn_context = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNCONTEXT"), ""));
00778       dyn_range = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNPOS"), ""));
00779       ast_channel_unlock(chan);
00780 
00781       if (!ast_strlen_zero(parkinglotname_copy)) {
00782          parkinglot_copy = find_parkinglot(parkinglotname_copy);
00783       }
00784       if (!parkinglot_copy) {
00785          parkinglot_copy = parkinglot_addref(default_parkinglot);
00786          ast_debug(1, "Using default parking lot for copy\n");
00787       }
00788       if (!(parkinglot = copy_parkinglot(parkinglotname, parkinglot_copy))) {
00789          ast_log(LOG_ERROR, "Could not build dynamic parking lot!\n");
00790       } else {
00791          if (!ast_strlen_zero(dyn_context)) {
00792             ast_copy_string(parkinglot->parking_con, dyn_context, sizeof(parkinglot->parking_con));
00793          }
00794          if (!ast_strlen_zero(dyn_range)) {
00795             if (sscanf(dyn_range, "%30d-%30d", &dyn_start, &dyn_end) != 2) {
00796                ast_log(LOG_WARNING, "Format for parking positions is a-b, where a and b are numbers\n");
00797             } else {
00798                parkinglot->parking_start = dyn_start;
00799                parkinglot->parking_stop = dyn_end;
00800             }
00801          }
00802          ao2_link(parkinglots, parkinglot);
00803       }
00804 
00805       if (parkinglot_copy) {
00806          /* unref our tempory copy */
00807          parkinglot_unref(parkinglot_copy);
00808          parkinglot_copy = NULL;
00809       }
00810    }
00811 
00812    if (!parkinglot) {
00813       parkinglot = parkinglot_addref(default_parkinglot);
00814    }
00815 
00816    ast_debug(1, "Parkinglot: %s\n", parkinglot->name);
00817 
00818    /* Allocate memory for parking data */
00819    if (!(pu = ast_calloc(1, sizeof(*pu)))) {
00820       parkinglot_unref(parkinglot);
00821       return NULL;
00822    }
00823 
00824    /* Lock parking list */
00825    AST_LIST_LOCK(&parkinglot->parkings);
00826    /* Check for channel variable PARKINGEXTEN */
00827    ast_channel_lock(chan);
00828    parkingexten = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGEXTEN"), ""));
00829    ast_channel_unlock(chan);
00830    if (!ast_strlen_zero(parkingexten)) {
00831       /*!\note The API forces us to specify a numeric parking slot, even
00832        * though the architecture would tend to support non-numeric extensions
00833        * (as are possible with SIP, for example).  Hence, we enforce that
00834        * limitation here.  If extout was not numeric, we could permit
00835        * arbitrary non-numeric extensions.
00836        */
00837         if (sscanf(parkingexten, "%30d", &parking_space) != 1 || parking_space < 0) {
00838          AST_LIST_UNLOCK(&parkinglot->parkings);
00839          parkinglot_unref(parkinglot);
00840             free(pu);
00841             ast_log(LOG_WARNING, "PARKINGEXTEN does not indicate a valid parking slot: '%s'.\n", parkingexten);
00842             return NULL;
00843         }
00844         snprintf(pu->parkingexten, sizeof(pu->parkingexten), "%d", parking_space);
00845 
00846       if (ast_exists_extension(NULL, parkinglot->parking_con, pu->parkingexten, 1, NULL)) {
00847          ast_log(LOG_WARNING, "Requested parking extension already exists: %s@%s\n", parkingexten, parkinglot->parking_con);
00848          AST_LIST_UNLOCK(&parkinglot->parkings);
00849          parkinglot_unref(parkinglot);
00850          ast_free(pu);
00851          return NULL;
00852       }
00853    } else {
00854       int start;
00855       struct parkeduser *cur = NULL;
00856 
00857       /* Select parking space within range */
00858       parking_range = parkinglot->parking_stop - parkinglot->parking_start + 1;
00859 
00860       if (ast_test_flag(args, AST_PARK_OPT_RANDOMIZE)) {
00861          start = ast_random() % (parkinglot->parking_stop - parkinglot->parking_start + 1);
00862       } else {
00863          start = parkinglot->parking_start;
00864       }
00865 
00866       for (i = start; 1; i++) {
00867          if (i == parkinglot->parking_stop + 1) {
00868             i = parkinglot->parking_start - 1;
00869             break;
00870          }
00871 
00872          AST_LIST_TRAVERSE(&parkinglot->parkings, cur, list) {
00873             if (cur->parkingnum == i) {
00874                break;
00875             }
00876          }
00877          if (!cur) {
00878             parking_space = i;
00879             break;
00880          }
00881       }
00882 
00883       if (i == start - 1 && cur) {
00884          ast_log(LOG_WARNING, "No more parking spaces\n");
00885          ast_free(pu);
00886          AST_LIST_UNLOCK(&parkinglot->parkings);
00887          parkinglot_unref(parkinglot);
00888          return NULL;
00889       }
00890       /* Set pointer for next parking */
00891       if (parkinglot->parkfindnext) 
00892          parkinglot->parking_offset = parking_space - parkinglot->parking_start + 1;
00893       snprintf(pu->parkingexten, sizeof(pu->parkingexten), "%d", parking_space);
00894    }
00895 
00896    pu->notquiteyet = 1;
00897    pu->parkingnum = parking_space;
00898    pu->parkinglot = parkinglot;
00899    AST_LIST_INSERT_TAIL(&parkinglot->parkings, pu, list);
00900 
00901    return pu;
00902 }
00903 
00904 /* Park a call */
00905 static int park_call_full(struct ast_channel *chan, struct ast_channel *peer, struct ast_park_call_args *args)
00906 {
00907    struct ast_context *con;
00908    int parkingnum_copy;
00909    struct parkeduser *pu = args->pu;
00910    const char *event_from;
00911 
00912    if (pu == NULL)
00913       args->pu = pu = park_space_reserve(chan, peer, args);
00914    if (pu == NULL)
00915       return 1; /* Continue execution if possible */
00916 
00917    snprintf(pu->parkingexten, sizeof(pu->parkingexten), "%d", pu->parkingnum);
00918 
00919    chan->appl = "Parked Call";
00920    chan->data = NULL;
00921 
00922    pu->chan = chan;
00923 
00924    /* Put the parked channel on hold if we have two different channels */
00925    if (chan != peer) {
00926       if (ast_test_flag(args, AST_PARK_OPT_RINGING)) {
00927          ast_indicate(pu->chan, AST_CONTROL_RINGING);
00928       } else {
00929          ast_indicate_data(pu->chan, AST_CONTROL_HOLD, 
00930             S_OR(pu->parkinglot->mohclass, NULL),
00931             !ast_strlen_zero(pu->parkinglot->mohclass) ? strlen(pu->parkinglot->mohclass) + 1 : 0);
00932       }
00933    }
00934    
00935    pu->start = ast_tvnow();
00936    pu->parkingtime = (args->timeout > 0) ? args->timeout : pu->parkinglot->parkingtime;
00937    parkingnum_copy = pu->parkingnum;
00938    if (args->extout)
00939       *(args->extout) = pu->parkingnum;
00940 
00941    if (peer) { 
00942       /* This is so ugly that it hurts, but implementing get_base_channel() on local channels
00943          could have ugly side effects.  We could have transferer<->local,1<->local,2<->parking
00944          and we need the callback name to be that of transferer.  Since local,1/2 have the same
00945          name we can be tricky and just grab the bridged channel from the other side of the local
00946       */
00947       if (!strcasecmp(peer->tech->type, "Local")) {
00948          struct ast_channel *tmpchan, *base_peer;
00949          char other_side[AST_CHANNEL_NAME];
00950          char *c;
00951          ast_copy_string(other_side, S_OR(args->orig_chan_name, peer->name), sizeof(other_side));
00952          if ((c = strrchr(other_side, ';'))) {
00953             *++c = '1';
00954          }
00955          if ((tmpchan = ast_channel_get_by_name(other_side))) {
00956             ast_channel_lock(tmpchan);
00957             if ((base_peer = ast_bridged_channel(tmpchan))) {
00958                ast_copy_string(pu->peername, base_peer->name, sizeof(pu->peername));
00959             }
00960             ast_channel_unlock(tmpchan);
00961             tmpchan = ast_channel_unref(tmpchan);
00962          }
00963       } else {
00964          ast_copy_string(pu->peername, S_OR(args->orig_chan_name, peer->name), sizeof(pu->peername));
00965       }
00966    }
00967 
00968    /* Remember what had been dialed, so that if the parking
00969       expires, we try to come back to the same place */
00970 
00971    pu->options_specified = (!ast_strlen_zero(args->return_con) || !ast_strlen_zero(args->return_ext) || args->return_pri);
00972 
00973    /* If extension has options specified, they override all other possibilities
00974    such as the returntoorigin flag and transferred context. Information on
00975    extension options is lost here, so we set a flag */
00976 
00977    ast_copy_string(pu->context, 
00978       S_OR(args->return_con, S_OR(chan->macrocontext, chan->context)), 
00979       sizeof(pu->context));
00980    ast_copy_string(pu->exten, 
00981       S_OR(args->return_ext, S_OR(chan->macroexten, chan->exten)), 
00982       sizeof(pu->exten));
00983    pu->priority = args->return_pri ? args->return_pri : 
00984       (chan->macropriority ? chan->macropriority : chan->priority);
00985 
00986    /* If parking a channel directly, don't quiet yet get parking running on it.
00987     * All parking lot entries are put into the parking lot with notquiteyet on. */
00988    if (peer != chan) 
00989       pu->notquiteyet = 0;
00990 
00991    /* Wake up the (presumably select()ing) thread */
00992    pthread_kill(parking_thread, SIGURG);
00993    ast_verb(2, "Parked %s on %d (lot %s). Will timeout back to extension [%s] %s, %d in %d seconds\n", pu->chan->name, pu->parkingnum, pu->parkinglot->name, pu->context, pu->exten, pu->priority, (pu->parkingtime/1000));
00994 
00995    ast_cel_report_event(pu->chan, AST_CEL_PARK_START, NULL, pu->parkinglot->name, peer);
00996 
00997    if (peer) {
00998       event_from = peer->name;
00999    } else {
01000       event_from = pbx_builtin_getvar_helper(chan, "BLINDTRANSFER");
01001    }
01002 
01003    ast_manager_event(pu->chan, EVENT_FLAG_CALL, "ParkedCall",
01004       "Exten: %s\r\n"
01005       "Channel: %s\r\n"
01006       "Parkinglot: %s\r\n"
01007       "From: %s\r\n"
01008       "Timeout: %ld\r\n"
01009       "CallerIDNum: %s\r\n"
01010       "CallerIDName: %s\r\n"
01011       "Uniqueid: %s\r\n",
01012       pu->parkingexten, pu->chan->name, pu->parkinglot->name, event_from ? event_from : "",
01013       (long)pu->start.tv_sec + (long)(pu->parkingtime/1000) - (long)time(NULL),
01014       S_COR(pu->chan->caller.id.number.valid, pu->chan->caller.id.number.str, "<unknown>"),
01015       S_COR(pu->chan->caller.id.name.valid, pu->chan->caller.id.name.str, "<unknown>"),
01016       pu->chan->uniqueid
01017       );
01018 
01019    if (peer && adsipark && ast_adsi_available(peer)) {
01020       adsi_announce_park(peer, pu->parkingexten);  /* Only supports parking numbers */
01021       ast_adsi_unload_session(peer);
01022    }
01023 
01024    con = ast_context_find_or_create(NULL, NULL, pu->parkinglot->parking_con, registrar);
01025    if (!con)   /* Still no context? Bad */
01026       ast_log(LOG_ERROR, "Parking context '%s' does not exist and unable to create\n", pu->parkinglot->parking_con);
01027    if (con) {
01028       if (!ast_add_extension2(con, 1, pu->parkingexten, 1, NULL, NULL, parkedcall, ast_strdup(pu->parkingexten), ast_free_ptr, registrar))
01029          notify_metermaids(pu->parkingexten, pu->parkinglot->parking_con, AST_DEVICE_INUSE);
01030    }
01031 
01032    AST_LIST_UNLOCK(&pu->parkinglot->parkings);
01033 
01034    /* Only say number if it's a number and the channel hasn't been masqueraded away */
01035    if (peer && !ast_test_flag(args, AST_PARK_OPT_SILENCE) && (ast_strlen_zero(args->orig_chan_name) || !strcasecmp(peer->name, args->orig_chan_name))) {
01036       /* If a channel is masqueraded into peer while playing back the parking slot number do not continue playing it back. This is the case if an attended transfer occurs. */
01037       ast_set_flag(peer, AST_FLAG_MASQ_NOSTREAM);
01038       /* Tell the peer channel the number of the parking space */
01039       ast_say_digits(peer, pu->parkingnum, "", peer->language);
01040       ast_clear_flag(peer, AST_FLAG_MASQ_NOSTREAM);
01041    }
01042    if (peer == chan) { /* pu->notquiteyet = 1 */
01043       /* Wake up parking thread if we're really done */
01044       ast_indicate_data(pu->chan, AST_CONTROL_HOLD, 
01045          S_OR(pu->parkinglot->mohclass, NULL),
01046          !ast_strlen_zero(pu->parkinglot->mohclass) ? strlen(pu->parkinglot->mohclass) + 1 : 0);
01047       pu->notquiteyet = 0;
01048       pthread_kill(parking_thread, SIGURG);
01049    }
01050    return 0;
01051 }
01052 
01053 /*! \brief Park a call */
01054 int ast_park_call(struct ast_channel *chan, struct ast_channel *peer, int timeout, const char *parkexten, int *extout)
01055 {
01056    struct ast_parkinglot *found_lot = ao2_callback(parkinglots, 0, find_parkinglot_by_exten_cb, (void *) parkexten);
01057 
01058    struct ast_park_call_args args = {
01059       .timeout = timeout,
01060       .extout = extout,
01061       .parkinglot = found_lot,
01062    };
01063 
01064    return park_call_full(chan, peer, &args);
01065 }
01066 
01067 /*!
01068  * \param rchan is the transferee
01069  * \param peer is the transferer
01070  */
01071 static int masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout, int play_announcement, struct ast_park_call_args *args)
01072 {
01073    struct ast_channel *chan;
01074    struct ast_frame *f;
01075    struct ast_park_call_args park_args = {0,};
01076 
01077    if (!args) {
01078       args = &park_args;
01079       args->timeout = timeout;
01080       args->extout = extout;
01081    }
01082 
01083    if ((args->pu = park_space_reserve(rchan, peer, args)) == NULL) {
01084       if (peer) {
01085          ast_stream_and_wait(peer, "pbx-parkingfailed", "");
01086       }
01087       return AST_FEATURE_RETURN_PARKFAILED;
01088    }
01089 
01090    /* Make a new, fake channel that we'll use to masquerade in the real one */
01091    if (!(chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, rchan->accountcode, rchan->exten, rchan->context, rchan->linkedid, rchan->amaflags, "Parked/%s",rchan->name))) {
01092       ast_log(LOG_WARNING, "Unable to create parked channel\n");
01093       return -1;
01094    }
01095 
01096    /* Make formats okay */
01097    chan->readformat = rchan->readformat;
01098    chan->writeformat = rchan->writeformat;
01099    ast_channel_masquerade(chan, rchan);
01100 
01101    /* Setup the extensions and such */
01102    set_c_e_p(chan, rchan->context, rchan->exten, rchan->priority);
01103 
01104    /* Setup the macro extension and such */
01105    ast_copy_string(chan->macrocontext,rchan->macrocontext,sizeof(chan->macrocontext));
01106    ast_copy_string(chan->macroexten,rchan->macroexten,sizeof(chan->macroexten));
01107    chan->macropriority = rchan->macropriority;
01108 
01109    /* Make the masq execute */
01110    if ((f = ast_read(chan)))
01111       ast_frfree(f);
01112 
01113    if (peer == rchan) {
01114       peer = chan;
01115    }
01116 
01117    if (peer && (!play_announcement && args == &park_args)) {
01118       args->orig_chan_name = ast_strdupa(peer->name);
01119    }
01120 
01121    /* parking space reserved, return code check unnecessary */
01122    park_call_full(chan, peer, args);
01123 
01124    return 0;
01125 }
01126 
01127 /* Park call via masqueraded channel */
01128 int ast_masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout)
01129 {
01130    return masq_park_call(rchan, peer, timeout, extout, 0, NULL);
01131 }
01132 
01133 static int masq_park_call_announce(struct ast_channel *rchan, struct ast_channel *peer, struct ast_park_call_args *args)
01134 {
01135    return masq_park_call(rchan, peer, 0, NULL, 1, args);
01136 }
01137 
01138 #ifdef TEST_FRAMEWORK
01139 static int fake_fixup(struct ast_channel *clonechan, struct ast_channel *original)
01140 {
01141    return 0;
01142 }
01143 
01144 static struct ast_channel *create_test_channel(const struct ast_channel_tech *fake_tech)
01145 {
01146    struct ast_channel *test_channel1;
01147    if (!(test_channel1 = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL,
01148         NULL, NULL, 0, 0, "TestChannel1"))) {
01149       return NULL;
01150    }
01151 
01152    /* normally this is done in the channel driver */
01153    test_channel1->nativeformats = AST_FORMAT_GSM;
01154    test_channel1->writeformat = AST_FORMAT_GSM;
01155    test_channel1->rawwriteformat = AST_FORMAT_GSM;
01156    test_channel1->readformat = AST_FORMAT_GSM;
01157    test_channel1->rawreadformat = AST_FORMAT_GSM;
01158    test_channel1->tech = fake_tech;
01159 
01160    return test_channel1;
01161 }
01162 
01163 static int unpark_test_channel(struct ast_channel *toremove, struct ast_park_call_args *args)
01164 {
01165    struct ast_context *con;
01166    struct parkeduser *pu_toremove;
01167    args->pu->notquiteyet = 1; /* go ahead and stop processing the test parking */
01168    AST_LIST_LOCK(&args->pu->parkinglot->parkings);
01169    AST_LIST_TRAVERSE_SAFE_BEGIN(&args->pu->parkinglot->parkings, pu_toremove, list) {
01170       con = ast_context_find(args->pu->parkinglot->parking_con);
01171       if (con) {
01172          if (ast_context_remove_extension2(con, args->pu->parkingexten, 1, NULL, 0)) {
01173             ast_log(LOG_WARNING, "Whoa, failed to remove the parking extension!\n");
01174             return -1;
01175          } else {
01176             notify_metermaids(args->pu->parkingexten, pu_toremove->parkinglot->parking_con, AST_DEVICE_NOT_INUSE);
01177          }
01178       } else {
01179          ast_log(LOG_WARNING, "Whoa, no parking context?\n");
01180          return -1;
01181       }
01182       if (pu_toremove == args->pu) {
01183          AST_LIST_REMOVE_CURRENT(list);
01184          break;
01185       }
01186    }
01187    AST_LIST_TRAVERSE_SAFE_END;
01188    AST_LIST_UNLOCK(&args->pu->parkinglot->parkings);
01189 
01190    /* the only way this would be unsafe is if a timeout occurred, which is set at 45 sec */
01191    ast_free(args->pu);
01192    args->pu = NULL;
01193 
01194    ast_hangup(toremove);
01195    return 0;
01196 }
01197 
01198 AST_TEST_DEFINE(features_test)
01199 {
01200    int saved_parkeddynamic;
01201    struct ast_channel *test_channel1 = NULL;
01202    struct ast_channel *parked_chan = NULL;
01203    struct ast_parkinglot *dynlot = NULL;
01204    struct ast_park_call_args args = {
01205       .timeout = DEFAULT_PARK_TIME,
01206    };
01207 
01208    int res = -1;
01209 
01210    static const struct ast_channel_tech fake_tech = {
01211       .fixup = fake_fixup, /* silence warning from masquerade */
01212    };
01213 
01214    static const char unique_parkinglot[] = "myuniquetestparkinglot3141592654";
01215    static const char parkinglot_range[] = "750-760";
01216 
01217    switch (cmd) {
01218    case TEST_INIT:
01219       info->name = "features_test";
01220       info->category = "/main/features/";
01221       info->summary = "Features unit test";
01222       info->description =
01223          "Tests whether parking respects PARKINGLOT settings";
01224       return AST_TEST_NOT_RUN;
01225    case TEST_EXECUTE:
01226       break;
01227    }
01228 
01229    /* changing a config option is a bad practice, but must be done in this case */
01230    saved_parkeddynamic = parkeddynamic;
01231    parkeddynamic = 1;
01232 
01233    if (!(test_channel1 = create_test_channel(&fake_tech))) {
01234       goto exit_features_test;
01235    }
01236 
01237    ast_test_status_update(test, "Test parking functionality with defaults\n");
01238    if (park_call_full(test_channel1, NULL, &args)) {
01239       goto exit_features_test;
01240    }
01241    if (unpark_test_channel(test_channel1, &args)) {
01242       goto exit_features_test;
01243    }
01244 
01245    ast_test_status_update(test, "Check that certain parking options are respected\n");
01246    if (!(test_channel1 = create_test_channel(&fake_tech))) {
01247       goto exit_features_test;
01248    }
01249    pbx_builtin_setvar_helper(test_channel1, "PARKINGLOT", unique_parkinglot);
01250    pbx_builtin_setvar_helper(test_channel1, "PARKINGDYNPOS", parkinglot_range);
01251    if (park_call_full(test_channel1, NULL, &args)) {
01252       goto exit_features_test;
01253    }
01254    /* grab newly created parking lot for destruction in the end */
01255    dynlot = args.pu->parkinglot;
01256    if (!args.pu->parkingnum == 750 || strcasecmp(args.pu->parkinglot->name, unique_parkinglot)) {
01257       ast_test_status_update(test, "Parking settings were not respected\n");
01258       goto exit_features_test;
01259    } else {
01260       ast_test_status_update(test, "Parking settings for non-masquerading park verified\n");
01261    }
01262    if (unpark_test_channel(test_channel1, &args)) {
01263       goto exit_features_test;
01264    }
01265 
01266    ast_test_status_update(test, "Check #2 that certain parking options are respected\n");
01267    if (!(test_channel1 = create_test_channel(&fake_tech))) {
01268       goto exit_features_test;
01269    }
01270    pbx_builtin_setvar_helper(test_channel1, "PARKINGLOT", unique_parkinglot);
01271    pbx_builtin_setvar_helper(test_channel1, "PARKINGDYNPOS", parkinglot_range);
01272    if (masq_park_call(test_channel1, NULL, 0, NULL, 0, &args) == AST_FEATURE_RETURN_PARKFAILED) {
01273       goto exit_features_test;
01274    }
01275    /* hangup zombie channel */
01276    ast_hangup(test_channel1);
01277    test_channel1 = NULL;
01278    if (!args.pu->parkingnum == 750 || strcasecmp(args.pu->parkinglot->name, unique_parkinglot)) {
01279       ast_test_status_update(test, "Parking settings were not respected\n");
01280       goto exit_features_test;
01281    } else {
01282       ast_test_status_update(test, "Parking settings for masquerading park verified\n");
01283    }
01284    /* find the real channel */
01285    parked_chan = ast_channel_get_by_name("TestChannel1");
01286    if (unpark_test_channel(parked_chan, &args)) {
01287       goto exit_features_test;
01288    }
01289 
01290    res = 0;
01291 
01292 exit_features_test:
01293 
01294    if (test_channel1) {
01295       ast_hangup(test_channel1);
01296    }
01297 
01298    /* careful, if PARKINGDYNCONTEXT is tested, need to delete context */
01299    ao2_unlink(parkinglots, dynlot);
01300    parkeddynamic = saved_parkeddynamic;
01301    return res ? AST_TEST_FAIL : AST_TEST_PASS;
01302 }
01303 #endif
01304 
01305 
01306 /*!
01307  * \brief set caller and callee according to the direction
01308  * \param caller, callee, peer, chan, sense
01309  *
01310  * Detect who triggered feature and set callee/caller variables accordingly
01311 */
01312 static void set_peers(struct ast_channel **caller, struct ast_channel **callee,
01313    struct ast_channel *peer, struct ast_channel *chan, int sense)
01314 {
01315    if (sense == FEATURE_SENSE_PEER) {
01316       *caller = peer;
01317       *callee = chan;
01318    } else {
01319       *callee = peer;
01320       *caller = chan;
01321    }
01322 }
01323 
01324 static int parkcall_helper(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, struct ast_park_call_args *args)
01325 {
01326    int res = 0;
01327 
01328    if (args) {
01329       ast_debug(1, "Parkinglot specified for builtin_parkcall: %s\n", args->parkinglot->name);
01330    }
01331 
01332    /* we used to set chan's exten and priority to "s" and 1
01333       here, but this generates (in some cases) an invalid
01334       extension, and if "s" exists, could errantly
01335       cause execution of extensions you don't expect. It
01336       makes more sense to let nature take its course
01337       when chan finishes, and let the pbx do its thing
01338       and hang up when the park is over.
01339    */
01340    if (chan->_state != AST_STATE_UP)
01341       res = ast_answer(chan);
01342    if (!res)
01343       res = ast_safe_sleep(chan, 1000);
01344 
01345    if (!res) { /* one direction used to call park_call.... */
01346       struct ast_channel *parker;
01347       struct ast_channel *parkee;
01348       set_peers(&parker, &parkee, peer, chan, sense);
01349       res = masq_park_call_announce(parkee, parker, args);
01350       /* PBX should hangup zombie channel if a masquerade actually occurred (res=0) */
01351    }
01352 
01353    return res;
01354 }
01355 
01356 /*! 
01357  * \brief support routing for one touch call parking
01358  * \param chan channel parking call
01359  * \param peer channel to be parked
01360  * \param config unsed
01361  * \param code unused
01362  * \param sense feature options
01363  *
01364  * \param data
01365  * Setup channel, set return exten,priority to 's,1'
01366  * answer chan, sleep chan, park call
01367 */
01368 static int builtin_parkcall(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
01369 {
01370    return parkcall_helper(chan, peer, config, code, sense, NULL);
01371 }
01372 
01373 /*! \brief Play message to both caller and callee in bridged call, plays synchronously, autoservicing the
01374    other channel during the message, so please don't use this for very long messages
01375  */
01376 static int play_message_in_bridged_call(struct ast_channel *caller_chan, struct ast_channel *callee_chan, const char *audiofile)
01377 {
01378    /* First play for caller, put other channel on auto service */
01379    if (ast_autoservice_start(callee_chan))
01380       return -1;
01381    ast_autoservice_ignore(callee_chan, AST_FRAME_DTMF_END);
01382    if (ast_stream_and_wait(caller_chan, audiofile, "")) {
01383       ast_log(LOG_WARNING, "Failed to play automon message!\n");
01384       ast_autoservice_stop(callee_chan);
01385       return -1;
01386    }
01387    if (ast_autoservice_stop(callee_chan))
01388       return -1;
01389    /* Then play for callee, put other channel on auto service */
01390    if (ast_autoservice_start(caller_chan))
01391       return -1;
01392    ast_autoservice_ignore(caller_chan, AST_FRAME_DTMF_END);
01393    if (ast_stream_and_wait(callee_chan, audiofile, "")) {
01394       ast_log(LOG_WARNING, "Failed to play automon message !\n");
01395       ast_autoservice_stop(caller_chan);
01396       return -1;
01397    }
01398    if (ast_autoservice_stop(caller_chan))
01399       return -1;
01400    return(0);
01401 }
01402 
01403 /*!
01404  * \brief Monitor a channel by DTMF
01405  * \param chan channel requesting monitor
01406  * \param peer channel to be monitored
01407  * \param config
01408  * \param code
01409  * \param sense feature options
01410  *
01411  * \param data
01412  * Check monitor app enabled, setup channels, both caller/callee chans not null
01413  * get TOUCH_MONITOR variable for filename if exists, exec monitor app.
01414  * \retval AST_FEATURE_RETURN_SUCCESS on success.
01415  * \retval -1 on error.
01416 */
01417 static int builtin_automonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
01418 {
01419    char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
01420    int x = 0;
01421    size_t len;
01422    struct ast_channel *caller_chan, *callee_chan;
01423    const char *automon_message_start = NULL;
01424    const char *automon_message_stop = NULL;
01425 
01426    if (!monitor_ok) {
01427       ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
01428       return -1;
01429    }
01430 
01431    if (!monitor_app && !(monitor_app = pbx_findapp("Monitor"))) {
01432       monitor_ok = 0;
01433       ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
01434       return -1;
01435    }
01436 
01437    set_peers(&caller_chan, &callee_chan, peer, chan, sense);
01438    if (caller_chan) {   /* Find extra messages */
01439       automon_message_start = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_START");
01440       automon_message_stop = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_STOP");
01441    }
01442 
01443    if (!ast_strlen_zero(courtesytone)) {  /* Play courtesy tone if configured */
01444       if(play_message_in_bridged_call(caller_chan, callee_chan, courtesytone) == -1) {
01445          return -1;
01446       }
01447    }
01448    
01449    if (callee_chan->monitor) {
01450       ast_verb(4, "User hit '%s' to stop recording call.\n", code);
01451       if (!ast_strlen_zero(automon_message_stop)) {
01452          play_message_in_bridged_call(caller_chan, callee_chan, automon_message_stop);
01453       }
01454       callee_chan->monitor->stop(callee_chan, 1);
01455       return AST_FEATURE_RETURN_SUCCESS;
01456    }
01457 
01458    if (caller_chan && callee_chan) {
01459       const char *touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_FORMAT");
01460       const char *touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR");
01461       const char *touch_monitor_prefix = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_PREFIX");
01462 
01463       if (!touch_format)
01464          touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_FORMAT");
01465 
01466       if (!touch_monitor)
01467          touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR");
01468    
01469       if (!touch_monitor_prefix)
01470          touch_monitor_prefix = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_PREFIX");
01471    
01472       if (touch_monitor) {
01473          len = strlen(touch_monitor) + 50;
01474          args = alloca(len);
01475          touch_filename = alloca(len);
01476          snprintf(touch_filename, len, "%s-%ld-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), touch_monitor);
01477          snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
01478       } else {
01479          caller_chan_id = ast_strdupa(S_COR(caller_chan->caller.id.number.valid,
01480             caller_chan->caller.id.number.str, caller_chan->name));
01481          callee_chan_id = ast_strdupa(S_COR(callee_chan->caller.id.number.valid,
01482             callee_chan->caller.id.number.str, callee_chan->name));
01483          len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
01484          args = alloca(len);
01485          touch_filename = alloca(len);
01486          snprintf(touch_filename, len, "%s-%ld-%s-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), caller_chan_id, callee_chan_id);
01487          snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
01488       }
01489 
01490       for(x = 0; x < strlen(args); x++) {
01491          if (args[x] == '/')
01492             args[x] = '-';
01493       }
01494       
01495       ast_verb(4, "User hit '%s' to record call. filename: %s\n", code, args);
01496 
01497       pbx_exec(callee_chan, monitor_app, args);
01498       pbx_builtin_setvar_helper(callee_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
01499       pbx_builtin_setvar_helper(caller_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
01500 
01501       if (!ast_strlen_zero(automon_message_start)) {  /* Play start message for both channels */
01502          play_message_in_bridged_call(caller_chan, callee_chan, automon_message_start);
01503       }
01504    
01505       return AST_FEATURE_RETURN_SUCCESS;
01506    }
01507    
01508    ast_log(LOG_NOTICE,"Cannot record the call. One or both channels have gone away.\n");  
01509    return -1;
01510 }
01511 
01512 static int builtin_automixmonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
01513 {
01514    char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
01515    int x = 0;
01516    size_t len;
01517    struct ast_channel *caller_chan, *callee_chan;
01518    const char *mixmonitor_spy_type = "MixMonitor";
01519    int count = 0;
01520 
01521    if (!mixmonitor_ok) {
01522       ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
01523       return -1;
01524    }
01525 
01526    if (!(mixmonitor_app = pbx_findapp("MixMonitor"))) {
01527       mixmonitor_ok = 0;
01528       ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
01529       return -1;
01530    }
01531 
01532    set_peers(&caller_chan, &callee_chan, peer, chan, sense);
01533 
01534    if (!ast_strlen_zero(courtesytone)) {
01535       if (ast_autoservice_start(callee_chan))
01536          return -1;
01537       ast_autoservice_ignore(callee_chan, AST_FRAME_DTMF_END);
01538       if (ast_stream_and_wait(caller_chan, courtesytone, "")) {
01539          ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
01540          ast_autoservice_stop(callee_chan);
01541          return -1;
01542       }
01543       if (ast_autoservice_stop(callee_chan))
01544          return -1;
01545    }
01546 
01547    ast_channel_lock(callee_chan);
01548    count = ast_channel_audiohook_count_by_source(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
01549    ast_channel_unlock(callee_chan);
01550 
01551    /* This means a mixmonitor is attached to the channel, running or not is unknown. */
01552    if (count > 0) {
01553       
01554       ast_verb(3, "User hit '%s' to stop recording call.\n", code);
01555 
01556       /* Make sure they are running */
01557       ast_channel_lock(callee_chan);
01558       count = ast_channel_audiohook_count_by_source_running(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
01559       ast_channel_unlock(callee_chan);
01560       if (count > 0) {
01561          if (!stopmixmonitor_ok) {
01562             ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
01563             return -1;
01564          }
01565          if (!(stopmixmonitor_app = pbx_findapp("StopMixMonitor"))) {
01566             stopmixmonitor_ok = 0;
01567             ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
01568             return -1;
01569          } else {
01570             pbx_exec(callee_chan, stopmixmonitor_app, "");
01571             return AST_FEATURE_RETURN_SUCCESS;
01572          }
01573       }
01574       
01575       ast_log(LOG_WARNING,"Stopped MixMonitors are attached to the channel.\n"); 
01576    }        
01577 
01578    if (caller_chan && callee_chan) {
01579       const char *touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR_FORMAT");
01580       const char *touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR");
01581 
01582       if (!touch_format)
01583          touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR_FORMAT");
01584 
01585       if (!touch_monitor)
01586          touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR");
01587 
01588       if (touch_monitor) {
01589          len = strlen(touch_monitor) + 50;
01590          args = alloca(len);
01591          touch_filename = alloca(len);
01592          snprintf(touch_filename, len, "auto-%ld-%s", (long)time(NULL), touch_monitor);
01593          snprintf(args, len, "%s.%s,b", touch_filename, (touch_format) ? touch_format : "wav");
01594       } else {
01595          caller_chan_id = ast_strdupa(S_COR(caller_chan->caller.id.number.valid,
01596             caller_chan->caller.id.number.str, caller_chan->name));
01597          callee_chan_id = ast_strdupa(S_COR(callee_chan->caller.id.number.valid,
01598             callee_chan->caller.id.number.str, callee_chan->name));
01599          len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
01600          args = alloca(len);
01601          touch_filename = alloca(len);
01602          snprintf(touch_filename, len, "auto-%ld-%s-%s", (long)time(NULL), caller_chan_id, callee_chan_id);
01603          snprintf(args, len, "%s.%s,b", touch_filename, S_OR(touch_format, "wav"));
01604       }
01605 
01606       for( x = 0; x < strlen(args); x++) {
01607          if (args[x] == '/')
01608             args[x] = '-';
01609       }
01610 
01611       ast_verb(3, "User hit '%s' to record call. filename: %s\n", code, touch_filename);
01612 
01613       pbx_exec(callee_chan, mixmonitor_app, args);
01614       pbx_builtin_setvar_helper(callee_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
01615       pbx_builtin_setvar_helper(caller_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
01616       return AST_FEATURE_RETURN_SUCCESS;
01617    
01618    }
01619 
01620    ast_log(LOG_NOTICE,"Cannot record the call. One or both channels have gone away.\n");
01621    return -1;
01622 
01623 }
01624 
01625 static int builtin_disconnect(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
01626 {
01627    ast_verb(4, "User hit '%s' to disconnect call.\n", code);
01628    return AST_FEATURE_RETURN_HANGUP;
01629 }
01630 
01631 static int finishup(struct ast_channel *chan)
01632 {
01633    ast_indicate(chan, AST_CONTROL_UNHOLD);
01634 
01635    return ast_autoservice_stop(chan);
01636 }
01637 
01638 /*!
01639  * \brief Find the context for the transfer
01640  * \param transferer
01641  * \param transferee
01642  * 
01643  * Grab the TRANSFER_CONTEXT, if fails try grabbing macrocontext.
01644  * \return a context string
01645 */
01646 static const char *real_ctx(struct ast_channel *transferer, struct ast_channel *transferee)
01647 {
01648    const char *s = pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT");
01649    if (ast_strlen_zero(s)) {
01650       s = pbx_builtin_getvar_helper(transferee, "TRANSFER_CONTEXT");
01651    }
01652    if (ast_strlen_zero(s)) { /* Use the non-macro context to transfer the call XXX ? */
01653       s = transferer->macrocontext;
01654    }
01655    if (ast_strlen_zero(s)) {
01656       s = transferer->context;
01657    }
01658    return s;  
01659 }
01660 
01661 /*!
01662  * \brief Blind transfer user to another extension
01663  * \param chan channel to be transfered
01664  * \param peer channel initiated blind transfer
01665  * \param config
01666  * \param code
01667  * \param data
01668  * \param sense  feature options
01669  * 
01670  * Place chan on hold, check if transferred to parkinglot extension,
01671  * otherwise check extension exists and transfer caller.
01672  * \retval AST_FEATURE_RETURN_SUCCESS.
01673  * \retval -1 on failure.
01674 */
01675 static int builtin_blindtransfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
01676 {
01677    struct ast_channel *transferer;
01678    struct ast_channel *transferee;
01679    const char *transferer_real_context;
01680    struct ast_parkinglot *found_lot = NULL;
01681    char xferto[256];
01682    int res, parkstatus = 0;
01683 
01684    set_peers(&transferer, &transferee, peer, chan, sense);
01685    transferer_real_context = real_ctx(transferer, transferee);
01686    /* Start autoservice on chan while we talk to the originator */
01687    ast_autoservice_start(transferee);
01688    ast_autoservice_ignore(transferee, AST_FRAME_DTMF_END);
01689    ast_indicate(transferee, AST_CONTROL_HOLD);
01690 
01691    memset(xferto, 0, sizeof(xferto));
01692 
01693    /* Transfer */
01694    res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
01695    if (res < 0) {
01696       finishup(transferee);
01697       return -1; /* error ? */
01698    }
01699    if (res > 0)   /* If they've typed a digit already, handle it */
01700       xferto[0] = (char) res;
01701 
01702    ast_stopstream(transferer);
01703    res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
01704    if (res < 0) {  /* hangup, would be 0 for invalid and 1 for valid */
01705       finishup(transferee);
01706       return res;
01707    }
01708 
01709    found_lot = ao2_callback(parkinglots, 0, find_parkinglot_by_exten_cb, &xferto);
01710    if (found_lot) {
01711       struct ast_park_call_args args = {
01712          .parkinglot = found_lot,
01713       };
01714       res = finishup(transferee);
01715       if (res)
01716          res = -1;
01717       else if (!(parkstatus = masq_park_call_announce(transferee, transferer, &args))) {  /* success */
01718          /* We return non-zero, but tell the PBX not to hang the channel when
01719             the thread dies -- We have to be careful now though.  We are responsible for 
01720             hanging up the channel, else it will never be hung up! */
01721 
01722          return 0;
01723       } else {
01724          ast_log(LOG_WARNING, "Unable to park call %s, parkstatus = %d\n", transferee->name, parkstatus);
01725       }
01726       /*! \todo XXX Maybe we should have another message here instead of invalid extension XXX */
01727    } else if (ast_exists_extension(transferee, transferer_real_context, xferto, 1,
01728       S_COR(transferer->caller.id.number.valid, transferer->caller.id.number.str, NULL))) {
01729       ast_cel_report_event(transferer, AST_CEL_BLINDTRANSFER, NULL, xferto, transferee);
01730       pbx_builtin_setvar_helper(transferer, "BLINDTRANSFER", transferee->name);
01731       pbx_builtin_setvar_helper(transferee, "BLINDTRANSFER", transferer->name);
01732       res=finishup(transferee);
01733       if (!transferer->cdr) { /* this code should never get called (in a perfect world) */
01734          transferer->cdr=ast_cdr_alloc();
01735          if (transferer->cdr) {
01736             ast_cdr_init(transferer->cdr, transferer); /* initialize our channel's cdr */
01737             ast_cdr_start(transferer->cdr);
01738          }
01739       }
01740       if (transferer->cdr) {
01741          struct ast_cdr *swap = transferer->cdr;
01742          ast_log(LOG_DEBUG,"transferer=%s; transferee=%s; lastapp=%s; lastdata=%s; chan=%s; dstchan=%s\n",
01743                transferer->name, transferee->name, transferer->cdr->lastapp, transferer->cdr->lastdata, 
01744                transferer->cdr->channel, transferer->cdr->dstchannel);
01745          ast_log(LOG_DEBUG,"TRANSFEREE; lastapp=%s; lastdata=%s, chan=%s; dstchan=%s\n",
01746                transferee->cdr->lastapp, transferee->cdr->lastdata, transferee->cdr->channel, transferee->cdr->dstchannel);
01747          ast_log(LOG_DEBUG,"transferer_real_context=%s; xferto=%s\n", transferer_real_context, xferto);
01748          /* swap cdrs-- it will save us some time & work */
01749          transferer->cdr = transferee->cdr;
01750          transferee->cdr = swap;
01751       }
01752       if (!transferee->pbx) {
01753          /* Doh!  Use our handy async_goto functions */
01754          ast_verb(3, "Transferring %s to '%s' (context %s) priority 1\n"
01755                         ,transferee->name, xferto, transferer_real_context);
01756          if (ast_async_goto(transferee, transferer_real_context, xferto, 1))
01757             ast_log(LOG_WARNING, "Async goto failed :-(\n");
01758       } else {
01759          /* Set the channel's new extension, since it exists, using transferer context */
01760          ast_set_flag(transferee, AST_FLAG_BRIDGE_HANGUP_DONT); /* don't let the after-bridge code run the h-exten */
01761          ast_log(LOG_DEBUG,"ABOUT TO AST_ASYNC_GOTO, have a pbx... set HANGUP_DONT on chan=%s\n", transferee->name);
01762          if (ast_channel_connected_line_macro(transferee, transferer, &transferer->connected, 1, 0)) {
01763             ast_channel_update_connected_line(transferer, &transferer->connected, NULL);
01764          }
01765          set_c_e_p(transferee, transferer_real_context, xferto, 0);
01766       }
01767       check_goto_on_transfer(transferer);
01768       return res;
01769    } else {
01770       ast_verb(3, "Unable to find extension '%s' in context '%s'\n", xferto, transferer_real_context);
01771    }
01772    if (parkstatus != AST_FEATURE_RETURN_PARKFAILED && ast_stream_and_wait(transferer, xferfailsound, AST_DIGIT_ANY) < 0) { /* Play 'extension does not exist' */
01773       finishup(transferee);
01774       return -1;
01775    }
01776    ast_stopstream(transferer);
01777    res = finishup(transferee);
01778    if (res) {
01779       ast_verb(2, "Hungup during autoservice stop on '%s'\n", transferee->name);
01780       return res;
01781    }
01782    return AST_FEATURE_RETURN_SUCCESS;
01783 }
01784 
01785 /*!
01786  * \brief make channels compatible
01787  * \param c
01788  * \param newchan
01789  * \retval 0 on success.
01790  * \retval -1 on failure.
01791 */
01792 static int check_compat(struct ast_channel *c, struct ast_channel *newchan)
01793 {
01794    if (ast_channel_make_compatible(c, newchan) < 0) {
01795       ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n",
01796          c->name, newchan->name);
01797       ast_hangup(newchan);
01798       return -1;
01799    }
01800    return 0;
01801 }
01802 
01803 /*!
01804  * \brief Attended transfer
01805  * \param chan transfered user
01806  * \param peer person transfering call
01807  * \param config
01808  * \param code
01809  * \param sense feature options
01810  * 
01811  * \param data
01812  * Get extension to transfer to, if you cannot generate channel (or find extension) 
01813  * return to host channel. After called channel answered wait for hangup of transferer,
01814  * bridge call between transfer peer (taking them off hold) to attended transfer channel.
01815  *
01816  * \return -1 on failure
01817 */
01818 static int builtin_atxfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
01819 {
01820    struct ast_channel *transferer;
01821    struct ast_channel *transferee;
01822    const char *transferer_real_context;
01823    char xferto[256] = "";
01824    int res;
01825    int outstate=0;
01826    struct ast_channel *newchan;
01827    struct ast_channel *xferchan;
01828    struct ast_bridge_thread_obj *tobj;
01829    struct ast_bridge_config bconfig;
01830    struct ast_frame *f;
01831    int l;
01832    struct ast_party_connected_line connected_line;
01833    struct ast_datastore *features_datastore;
01834    struct ast_dial_features *dialfeatures = NULL;
01835    struct ast_parkinglot *parkinglot;
01836 
01837    ast_debug(1, "Executing Attended Transfer %s, %s (sense=%d) \n", chan->name, peer->name, sense);
01838    set_peers(&transferer, &transferee, peer, chan, sense);
01839    transferer_real_context = real_ctx(transferer, transferee);
01840    /* Start autoservice on chan while we talk to the originator */
01841    ast_autoservice_start(transferee);
01842    ast_autoservice_ignore(transferee, AST_FRAME_DTMF_END);
01843    ast_indicate(transferee, AST_CONTROL_HOLD);
01844    
01845    /* Transfer */
01846    res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
01847    if (res < 0) {
01848       finishup(transferee);
01849       return res;
01850    }
01851    if (res > 0) /* If they've typed a digit already, handle it */
01852       xferto[0] = (char) res;
01853 
01854    /* this is specific of atxfer */
01855    res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
01856    if (res < 0) {  /* hangup, would be 0 for invalid and 1 for valid */
01857       finishup(transferee);
01858       return res;
01859    }
01860    if (res == 0) {
01861       ast_log(LOG_WARNING, "Did not read data.\n");
01862       finishup(transferee);
01863       if (ast_stream_and_wait(transferer, "beeperr", ""))
01864          return -1;
01865       return AST_FEATURE_RETURN_SUCCESS;
01866    }
01867 
01868    /* valid extension, res == 1 */
01869    if (!ast_exists_extension(transferer, transferer_real_context, xferto, 1,
01870       S_COR(transferer->caller.id.number.valid, transferer->caller.id.number.str, NULL))) {
01871       ast_log(LOG_WARNING, "Extension %s does not exist in context %s\n",xferto,transferer_real_context);
01872       finishup(transferee);
01873       if (ast_stream_and_wait(transferer, "beeperr", ""))
01874          return -1;
01875       return AST_FEATURE_RETURN_SUCCESS;
01876    }
01877 
01878    /* If we are attended transfering to parking, just use parkcall_helper instead of trying to track all of
01879     * the different variables for handling this properly with a builtin_atxfer */
01880    parkinglot = ao2_callback(parkinglots, 0, find_parkinglot_by_exten_cb, &xferto);
01881    if (parkinglot) {
01882       struct ast_park_call_args args = {
01883          .parkinglot = parkinglot,
01884       };
01885       finishup(transferee);
01886       return parkcall_helper(chan, peer, config, code, sense, &args);
01887    }
01888 
01889    l = strlen(xferto);
01890    snprintf(xferto + l, sizeof(xferto) - l, "@%s/n", transferer_real_context);   /* append context */
01891 
01892    /* If we are performing an attended transfer and we have two channels involved then
01893       copy sound file information to play upon attended transfer completion */
01894    if (transferee) {
01895       const char *chan1_attended_sound = pbx_builtin_getvar_helper(transferer, "ATTENDED_TRANSFER_COMPLETE_SOUND");
01896       const char *chan2_attended_sound = pbx_builtin_getvar_helper(transferee, "ATTENDED_TRANSFER_COMPLETE_SOUND");
01897 
01898       if (!ast_strlen_zero(chan1_attended_sound)) {
01899          pbx_builtin_setvar_helper(transferer, "BRIDGE_PLAY_SOUND", chan1_attended_sound);
01900       }
01901       if (!ast_strlen_zero(chan2_attended_sound)) {
01902          pbx_builtin_setvar_helper(transferee, "BRIDGE_PLAY_SOUND", chan2_attended_sound);
01903       }
01904    }
01905 
01906    newchan = feature_request_and_dial(transferer, transferee, "Local",
01907       ast_best_codec(transferer->nativeformats),
01908       xferto, atxfernoanswertimeout, &outstate,
01909       transferer->caller.id.number.valid ? transferer->caller.id.number.str : NULL,
01910       transferer->caller.id.name.valid ? transferer->caller.id.name.str : NULL,
01911       1, transferer->language);
01912 
01913    ast_party_connected_line_init(&connected_line);
01914    if (!ast_check_hangup(transferer)) {
01915       int hangup_dont = 0;
01916 
01917       /* Transferer is up - old behaviour */
01918       ast_indicate(transferer, -1);
01919       if (!newchan) {
01920          finishup(transferee);
01921          /* any reason besides user requested cancel and busy triggers the failed sound */
01922          if (outstate != AST_CONTROL_UNHOLD && outstate != AST_CONTROL_BUSY &&
01923             ast_stream_and_wait(transferer, xferfailsound, ""))
01924             return -1;
01925          if (ast_stream_and_wait(transferer, xfersound, ""))
01926             ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
01927          return AST_FEATURE_RETURN_SUCCESS;
01928       }
01929 
01930       if (check_compat(transferer, newchan)) {
01931          /* we do mean transferee here, NOT transferer */
01932          finishup(transferee);
01933          return -1;
01934       }
01935       memset(&bconfig,0,sizeof(struct ast_bridge_config));
01936       ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
01937       ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
01938       /* We need to get the transferer's connected line information copied
01939        * at this point because he is likely to hang up during the bridge with
01940        * newchan. This info will be used down below before bridging the 
01941        * transferee and newchan
01942        *
01943        * As a result, we need to be sure to free this data before returning
01944        * or overwriting it.
01945        */
01946       ast_channel_lock(transferer);
01947       ast_party_connected_line_copy(&connected_line, &transferer->connected);
01948       ast_channel_unlock(transferer);
01949 
01950       /* ast_bridge_call clears AST_FLAG_BRIDGE_HANGUP_DONT, but we don't
01951          want that to happen here because we're also in another bridge already
01952        */
01953       if (ast_test_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT)) {
01954          hangup_dont = 1;
01955       }
01956       res = ast_bridge_call(transferer, newchan, &bconfig);
01957       if (hangup_dont) {
01958          ast_set_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT);
01959       }
01960 
01961       if (ast_check_hangup(newchan) || !ast_check_hangup(transferer)) {
01962          ast_hangup(newchan);
01963          if (ast_stream_and_wait(transferer, xfersound, ""))
01964             ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
01965          finishup(transferee);
01966          transferer->_softhangup = 0;
01967          ast_party_connected_line_free(&connected_line);
01968          return AST_FEATURE_RETURN_SUCCESS;
01969       }
01970 
01971       ast_cel_report_event(transferee, AST_CEL_ATTENDEDTRANSFER, NULL, NULL, newchan);
01972 
01973       if (check_compat(transferee, newchan)) {
01974          finishup(transferee);
01975          ast_party_connected_line_free(&connected_line);
01976          return -1;
01977       }
01978       ast_indicate(transferee, AST_CONTROL_UNHOLD);
01979 
01980       if ((ast_autoservice_stop(transferee) < 0)
01981        || (ast_waitfordigit(transferee, 100) < 0)
01982        || (ast_waitfordigit(newchan, 100) < 0)
01983        || ast_check_hangup(transferee)
01984        || ast_check_hangup(newchan)) {
01985          ast_hangup(newchan);
01986          ast_party_connected_line_free(&connected_line);
01987          return -1;
01988       }
01989       xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", transferee->linkedid, 0, "Transfered/%s", transferee->name);
01990       if (!xferchan) {
01991          ast_hangup(newchan);
01992          ast_party_connected_line_free(&connected_line);
01993          return -1;
01994       }
01995       /* Make formats okay */
01996       xferchan->visible_indication = transferer->visible_indication;
01997       xferchan->readformat = transferee->readformat;
01998       xferchan->writeformat = transferee->writeformat;
01999       ast_channel_masquerade(xferchan, transferee);
02000       ast_explicit_goto(xferchan, transferee->context, transferee->exten, transferee->priority);
02001       xferchan->_state = AST_STATE_UP;
02002       ast_clear_flag(xferchan, AST_FLAGS_ALL);
02003       xferchan->_softhangup = 0;
02004       if ((f = ast_read(xferchan)))
02005          ast_frfree(f);
02006       newchan->_state = AST_STATE_UP;
02007       ast_clear_flag(newchan, AST_FLAGS_ALL);
02008       newchan->_softhangup = 0;
02009       if (!(tobj = ast_calloc(1, sizeof(*tobj)))) {
02010          ast_hangup(xferchan);
02011          ast_hangup(newchan);
02012          ast_party_connected_line_free(&connected_line);
02013          return -1;
02014       }
02015 
02016       ast_channel_lock(newchan);
02017       if ((features_datastore = ast_channel_datastore_find(newchan, &dial_features_info, NULL))) {
02018             dialfeatures = features_datastore->data;
02019       }
02020       ast_channel_unlock(newchan);
02021 
02022       if (dialfeatures) {
02023          /* newchan should always be the callee and shows up as callee in dialfeatures, but for some reason
02024             I don't currently understand, the abilities of newchan seem to be stored on the caller side */
02025          ast_copy_flags(&(config->features_callee), &(dialfeatures->features_caller), AST_FLAGS_ALL);
02026          dialfeatures = NULL;
02027       }
02028 
02029       ast_channel_lock(xferchan);
02030       if ((features_datastore = ast_channel_datastore_find(xferchan, &dial_features_info, NULL))) {
02031          dialfeatures = features_datastore->data;
02032       }
02033       ast_channel_unlock(xferchan);
02034     
02035       if (dialfeatures) {
02036          ast_copy_flags(&(config->features_caller), &(dialfeatures->features_caller), AST_FLAGS_ALL);
02037       }
02038     
02039       tobj->chan = newchan;
02040       tobj->peer = xferchan;
02041       tobj->bconfig = *config;
02042 
02043       if (tobj->bconfig.end_bridge_callback_data_fixup) {
02044          tobj->bconfig.end_bridge_callback_data_fixup(&tobj->bconfig, tobj->peer, tobj->chan);
02045       }
02046 
02047       /* Due to a limitation regarding when callerID is set on a Local channel,
02048        * we use the transferer's connected line information here.
02049        */
02050 
02051       /* xferchan is transferee, and newchan is the transfer target
02052        * So...in a transfer, who is the caller and who is the callee?
02053        *
02054        * When the call is originally made, it is clear who is caller and callee.
02055        * When a transfer occurs, it is my humble opinion that the transferee becomes
02056        * the caller, and the transfer target is the callee.
02057        *
02058        * The problem is that these macros were set with the intention of the original
02059        * caller and callee taking those roles. A transfer can totally mess things up,
02060        * to be technical. What sucks even more is that you can't effectively change
02061        * the macros in the dialplan during the call from the transferer to the transfer
02062        * target because the transferee is stuck with whatever role he originally had.
02063        *
02064        * I think the answer here is just to make sure that it is well documented that
02065        * during a transfer, the transferee is the "caller" and the transfer target
02066        * is the "callee."
02067        *
02068        * This means that if party A calls party B, and party A transfers party B to
02069        * party C, then B has switched roles for the call. Now party B will have the
02070        * caller macro called on his channel instead of the callee macro.
02071        *
02072        * Luckily, the method by which the bridge is launched here ensures that the 
02073        * transferee is the "chan" on the bridge and the transfer target is the "peer,"
02074        * so my idea for the roles post-transfer does not require extensive code changes.
02075        */
02076       connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
02077       if (ast_channel_connected_line_macro(newchan, xferchan, &connected_line, 1, 0)) {
02078          ast_channel_update_connected_line(xferchan, &connected_line, NULL);
02079       }
02080       ast_channel_lock(xferchan);
02081       ast_connected_line_copy_from_caller(&connected_line, &xferchan->caller);
02082       ast_channel_unlock(xferchan);
02083       connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
02084       if (ast_channel_connected_line_macro(xferchan, newchan, &connected_line, 0, 0)) {
02085          ast_channel_update_connected_line(newchan, &connected_line, NULL);
02086       }
02087       ast_party_connected_line_free(&connected_line);
02088 
02089       if (ast_stream_and_wait(newchan, xfersound, ""))
02090          ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
02091       bridge_call_thread_launch(tobj);
02092       return -1;      /* XXX meaning the channel is bridged ? */
02093    } else if (!ast_check_hangup(transferee)) {
02094       /* act as blind transfer */
02095       if (ast_autoservice_stop(transferee) < 0) {
02096          ast_hangup(newchan);
02097          return -1;
02098       }
02099 
02100       if (!newchan) {
02101          unsigned int tries = 0;
02102          char *transferer_tech, *transferer_name = ast_strdupa(transferer->name);
02103 
02104          transferer_tech = strsep(&transferer_name, "/");
02105          transferer_name = strsep(&transferer_name, "-");
02106 
02107          if (ast_strlen_zero(transferer_name) || ast_strlen_zero(transferer_tech)) {
02108             ast_log(LOG_WARNING, "Transferer has invalid channel name: '%s'\n", transferer->name);
02109             if (ast_stream_and_wait(transferee, "beeperr", ""))
02110                return -1;
02111             return AST_FEATURE_RETURN_SUCCESS;
02112          }
02113 
02114          ast_log(LOG_NOTICE, "We're trying to call %s/%s\n", transferer_tech, transferer_name);
02115          newchan = feature_request_and_dial(transferee, NULL, transferer_tech,
02116             ast_best_codec(transferee->nativeformats),
02117             transferer_name, atxfernoanswertimeout, &outstate,
02118             transferee->caller.id.number.valid ? transferee->caller.id.number.str : NULL,
02119             transferee->caller.id.name.valid ? transferee->caller.id.name.str : NULL,
02120             0, transferer->language);
02121          while (!newchan && !atxferdropcall && tries < atxfercallbackretries) {
02122             /* Trying to transfer again */
02123             ast_autoservice_start(transferee);
02124             ast_autoservice_ignore(transferee, AST_FRAME_DTMF_END);
02125             ast_indicate(transferee, AST_CONTROL_HOLD);
02126 
02127             newchan = feature_request_and_dial(transferer, transferee, "Local",
02128                ast_best_codec(transferer->nativeformats),
02129                xferto, atxfernoanswertimeout, &outstate,
02130                transferer->caller.id.number.valid ? transferer->caller.id.number.str : NULL,
02131                transferer->caller.id.name.valid ? transferer->caller.id.name.str : NULL,
02132                1, transferer->language);
02133             if (ast_autoservice_stop(transferee) < 0) {
02134                if (newchan)
02135                   ast_hangup(newchan);
02136                return -1;
02137             }
02138             if (!newchan) {
02139                /* Transfer failed, sleeping */
02140                ast_debug(1, "Sleeping for %d ms before callback.\n", atxferloopdelay);
02141                ast_safe_sleep(transferee, atxferloopdelay);
02142                ast_debug(1, "Trying to callback...\n");
02143                newchan = feature_request_and_dial(transferee, NULL, transferer_tech,
02144                   ast_best_codec(transferee->nativeformats),
02145                   transferer_name, atxfernoanswertimeout, &outstate,
02146                   transferee->caller.id.number.valid ? transferee->caller.id.number.str : NULL,
02147                   transferee->caller.id.name.valid ? transferee->caller.id.name.str : NULL,
02148                   0, transferer->language);
02149             }
02150             tries++;
02151          }
02152       }
02153       if (!newchan)
02154          return -1;
02155 
02156       ast_cel_report_event(transferee, AST_CEL_ATTENDEDTRANSFER, NULL, NULL, newchan);
02157 
02158       /* newchan is up, we should prepare transferee and bridge them */
02159       if (check_compat(transferee, newchan)) {
02160          finishup(transferee);
02161          return -1;
02162       }
02163       ast_indicate(transferee, AST_CONTROL_UNHOLD);
02164 
02165       if ((ast_waitfordigit(transferee, 100) < 0)
02166          || (ast_waitfordigit(newchan, 100) < 0)
02167          || ast_check_hangup(transferee)
02168          || ast_check_hangup(newchan)) {
02169          ast_hangup(newchan);
02170          return -1;
02171       }
02172 
02173       xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", transferee->linkedid, 0, "Transfered/%s", transferee->name);
02174       if (!xferchan) {
02175          ast_hangup(newchan);
02176          return -1;
02177       }
02178       /* Make formats okay */
02179       xferchan->visible_indication = transferer->visible_indication;
02180       xferchan->readformat = transferee->readformat;
02181       xferchan->writeformat = transferee->writeformat;
02182       ast_channel_masquerade(xferchan, transferee);
02183       ast_explicit_goto(xferchan, transferee->context, transferee->exten, transferee->priority);
02184       xferchan->_state = AST_STATE_UP;
02185       ast_clear_flag(xferchan, AST_FLAGS_ALL);
02186       xferchan->_softhangup = 0;
02187       if ((f = ast_read(xferchan)))
02188          ast_frfree(f);
02189       newchan->_state = AST_STATE_UP;
02190       ast_clear_flag(newchan, AST_FLAGS_ALL);
02191       newchan->_softhangup = 0;
02192       if (!(tobj = ast_calloc(1, sizeof(*tobj)))) {
02193          ast_hangup(xferchan);
02194          ast_hangup(newchan);
02195          return -1;
02196       }
02197       tobj->chan = newchan;
02198       tobj->peer = xferchan;
02199       tobj->bconfig = *config;
02200       
02201       if (tobj->bconfig.end_bridge_callback_data_fixup) {
02202          tobj->bconfig.end_bridge_callback_data_fixup(&tobj->bconfig, tobj->peer, tobj->chan);
02203       }
02204 
02205       ast_channel_lock(newchan);
02206       ast_connected_line_copy_from_caller(&connected_line, &newchan->caller);
02207       ast_channel_unlock(newchan);
02208       connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
02209       if (ast_channel_connected_line_macro(newchan, xferchan, &connected_line, 1, 0)) {
02210          ast_channel_update_connected_line(xferchan, &connected_line, NULL);
02211       }
02212       ast_channel_lock(xferchan);
02213       ast_connected_line_copy_from_caller(&connected_line, &xferchan->caller);
02214       ast_channel_unlock(xferchan);
02215       connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
02216       if (ast_channel_connected_line_macro(xferchan, newchan, &connected_line, 0, 0)) {
02217          ast_channel_update_connected_line(newchan, &connected_line, NULL);
02218       }
02219 
02220       ast_party_connected_line_free(&connected_line);
02221       
02222       if (ast_stream_and_wait(newchan, xfersound, ""))
02223          ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
02224       bridge_call_thread_launch(tobj);
02225       return -1;      /* XXX meaning the channel is bridged ? */
02226    } else {
02227       /* Transferee hung up */
02228       finishup(transferee);
02229       /* At this point both the transferer transferee have hungup,
02230        * so if newchan is up, hang it up as it has no one to talk to */
02231       if (newchan) {
02232          ast_hangup(newchan);
02233       }
02234       return -1;
02235    }
02236 }
02237 
02238 /* add atxfer and automon as undefined so you can only use em if you configure them */
02239 #define FEATURES_COUNT ARRAY_LEN(builtin_features)
02240 
02241 AST_RWLOCK_DEFINE_STATIC(features_lock);
02242 
02243 static struct ast_call_feature builtin_features[] = {
02244    { AST_FEATURE_REDIRECT, "Blind Transfer", "blindxfer", "#", "#", builtin_blindtransfer, AST_FEATURE_FLAG_NEEDSDTMF, "" },
02245    { AST_FEATURE_REDIRECT, "Attended Transfer", "atxfer", "", "", builtin_atxfer, AST_FEATURE_FLAG_NEEDSDTMF, "" },
02246    { AST_FEATURE_AUTOMON, "One Touch Monitor", "automon", "", "", builtin_automonitor, AST_FEATURE_FLAG_NEEDSDTMF, "" },
02247    { AST_FEATURE_DISCONNECT, "Disconnect Call", "disconnect", "*", "*", builtin_disconnect, AST_FEATURE_FLAG_NEEDSDTMF, "" },
02248    { AST_FEATURE_PARKCALL, "Park Call", "parkcall", "", "", builtin_parkcall, AST_FEATURE_FLAG_NEEDSDTMF, "" },
02249    { AST_FEATURE_AUTOMIXMON, "One Touch MixMonitor", "automixmon", "", "", builtin_automixmonitor, AST_FEATURE_FLAG_NEEDSDTMF, "" },
02250 };
02251 
02252 
02253 static AST_RWLIST_HEAD_STATIC(feature_list, ast_call_feature);
02254 
02255 /*! \brief register new feature into feature_list*/
02256 void ast_register_feature(struct ast_call_feature *feature)
02257 {
02258    if (!feature) {
02259       ast_log(LOG_NOTICE,"You didn't pass a feature!\n");
02260       return;
02261    }
02262   
02263    AST_RWLIST_WRLOCK(&feature_list);
02264    AST_RWLIST_INSERT_HEAD(&feature_list,feature,feature_entry);
02265    AST_RWLIST_UNLOCK(&feature_list);
02266 
02267    ast_verb(2, "Registered Feature '%s'\n",feature->sname);
02268 }
02269 
02270 /*! 
02271  * \brief Add new feature group
02272  * \param fgname feature group name.
02273  *
02274  * Add new feature group to the feature group list insert at head of list.
02275  * \note This function MUST be called while feature_groups is locked.
02276 */
02277 static struct feature_group *register_group(const char *fgname)
02278 {
02279    struct feature_group *fg;
02280 
02281    if (!fgname) {
02282       ast_log(LOG_NOTICE, "You didn't pass a new group name!\n");
02283       return NULL;
02284    }
02285 
02286    if (!(fg = ast_calloc_with_stringfields(1, struct feature_group, 128))) {
02287       return NULL;
02288    }
02289 
02290    ast_string_field_set(fg, gname, fgname);
02291 
02292    AST_LIST_INSERT_HEAD(&feature_groups, fg, entry);
02293 
02294    ast_verb(2, "Registered group '%s'\n", fg->gname);
02295 
02296    return fg;
02297 }
02298 
02299 /*! 
02300  * \brief Add feature to group
02301  * \param fg feature group
02302  * \param exten
02303  * \param feature feature to add.
02304  *
02305  * Check fg and feature specified, add feature to list
02306  * \note This function MUST be called while feature_groups is locked. 
02307 */
02308 static void register_group_feature(struct feature_group *fg, const char *exten, struct ast_call_feature *feature)
02309 {
02310    struct feature_group_exten *fge;
02311 
02312    if (!fg) {
02313       ast_log(LOG_NOTICE, "You didn't pass a group!\n");
02314       return;
02315    }
02316 
02317    if (!feature) {
02318       ast_log(LOG_NOTICE, "You didn't pass a feature!\n");
02319       return;
02320    }
02321 
02322    if (!(fge = ast_calloc_with_stringfields(1, struct feature_group_exten, 128))) {
02323       return;
02324    }
02325 
02326    ast_string_field_set(fge, exten, S_OR(exten, feature->exten));
02327 
02328    fge->feature = feature;
02329 
02330    AST_LIST_INSERT_HEAD(&fg->features, fge, entry);
02331 
02332    ast_verb(2, "Registered feature '%s' for group '%s' at exten '%s'\n",
02333                feature->sname, fg->gname, fge->exten);
02334 }
02335 
02336 void ast_unregister_feature(struct ast_call_feature *feature)
02337 {
02338    if (!feature) {
02339       return;
02340    }
02341 
02342    AST_RWLIST_WRLOCK(&feature_list);
02343    AST_RWLIST_REMOVE(&feature_list, feature, feature_entry);
02344    AST_RWLIST_UNLOCK(&feature_list);
02345 
02346    ast_free(feature);
02347 }
02348 
02349 /*! \brief Remove all features in the list */
02350 static void ast_unregister_features(void)
02351 {
02352    struct ast_call_feature *feature;
02353 
02354    AST_RWLIST_WRLOCK(&feature_list);
02355    while ((feature = AST_RWLIST_REMOVE_HEAD(&feature_list, feature_entry))) {
02356       ast_free(feature);
02357    }
02358    AST_RWLIST_UNLOCK(&feature_list);
02359 }
02360 
02361 /*! \brief find a call feature by name */
02362 static struct ast_call_feature *find_dynamic_feature(const char *name)
02363 {
02364    struct ast_call_feature *tmp;
02365 
02366    AST_RWLIST_TRAVERSE(&feature_list, tmp, feature_entry) {
02367       if (!strcasecmp(tmp->sname, name)) {
02368          break;
02369       }
02370    }
02371 
02372    return tmp;
02373 }
02374 
02375 /*! \brief Remove all feature groups in the list */
02376 static void ast_unregister_groups(void)
02377 {
02378    struct feature_group *fg;
02379    struct feature_group_exten *fge;
02380 
02381    AST_RWLIST_WRLOCK(&feature_groups);
02382    while ((fg = AST_LIST_REMOVE_HEAD(&feature_groups, entry))) {
02383       while ((fge = AST_LIST_REMOVE_HEAD(&fg->features, entry))) {
02384          ast_string_field_free_memory(fge);
02385          ast_free(fge);
02386       }
02387 
02388       ast_string_field_free_memory(fg);
02389       ast_free(fg);
02390    }
02391    AST_RWLIST_UNLOCK(&feature_groups);
02392 }
02393 
02394 /*! 
02395  * \brief Find a group by name 
02396  * \param name feature name
02397  * \retval feature group on success.
02398  * \retval NULL on failure.
02399 */
02400 static struct feature_group *find_group(const char *name)
02401 {
02402    struct feature_group *fg = NULL;
02403 
02404    AST_LIST_TRAVERSE(&feature_groups, fg, entry) {
02405       if (!strcasecmp(fg->gname, name))
02406          break;
02407    }
02408 
02409    return fg;
02410 }
02411 
02412 void ast_rdlock_call_features(void)
02413 {
02414    ast_rwlock_rdlock(&features_lock);
02415 }
02416 
02417 void ast_unlock_call_features(void)
02418 {
02419    ast_rwlock_unlock(&features_lock);
02420 }
02421 
02422 struct ast_call_feature *ast_find_call_feature(const char *name)
02423 {
02424    int x;
02425    for (x = 0; x < FEATURES_COUNT; x++) {
02426       if (!strcasecmp(name, builtin_features[x].sname))
02427          return &builtin_features[x];
02428    }
02429    return NULL;
02430 }
02431 
02432 /*!
02433  * \brief exec an app by feature 
02434  * \param chan,peer,config,code,sense,data
02435  *
02436  * Find a feature, determine which channel activated
02437  * \retval AST_FEATURE_RETURN_NO_HANGUP_PEER
02438  * \retval -1 error.
02439  * \retval -2 when an application cannot be found.
02440 */
02441 static int feature_exec_app(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
02442 {
02443    struct ast_app *app;
02444    struct ast_call_feature *feature = data;
02445    struct ast_channel *work, *idle;
02446    int res;
02447 
02448    if (!feature) { /* shouldn't ever happen! */
02449       ast_log(LOG_NOTICE, "Found feature before, but at execing we've lost it??\n");
02450       return -1; 
02451    }
02452 
02453    if (sense == FEATURE_SENSE_CHAN) {
02454       if (!ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER))
02455          return AST_FEATURE_RETURN_KEEPTRYING;
02456       if (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF)) {
02457          work = chan;
02458          idle = peer;
02459       } else {
02460          work = peer;
02461          idle = chan;
02462       }
02463    } else {
02464       if (!ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE))
02465          return AST_FEATURE_RETURN_KEEPTRYING;
02466       if (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF)) {
02467          work = peer;
02468          idle = chan;
02469       } else {
02470          work = chan;
02471          idle = peer;
02472       }
02473    }
02474 
02475    if (!(app = pbx_findapp(feature->app))) {
02476       ast_log(LOG_WARNING, "Could not find application (%s)\n", feature->app);
02477       return -2;
02478    }
02479 
02480    ast_autoservice_start(idle);
02481    ast_autoservice_ignore(idle, AST_FRAME_DTMF_END);
02482    
02483    if(work && idle) {
02484       pbx_builtin_setvar_helper(work, "DYNAMIC_PEERNAME", idle->name);
02485       pbx_builtin_setvar_helper(idle, "DYNAMIC_PEERNAME", work->name);
02486       pbx_builtin_setvar_helper(work, "DYNAMIC_FEATURENAME", feature->sname);
02487       pbx_builtin_setvar_helper(idle, "DYNAMIC_FEATURENAME", feature->sname);
02488    }
02489 
02490    if (!ast_strlen_zero(feature->moh_class))
02491       ast_moh_start(idle, feature->moh_class, NULL);
02492 
02493    res = pbx_exec(work, app, feature->app_args);
02494 
02495    if (!ast_strlen_zero(feature->moh_class))
02496       ast_moh_stop(idle);
02497 
02498    ast_autoservice_stop(idle);
02499 
02500    if (res) {
02501       return AST_FEATURE_RETURN_SUCCESSBREAK;
02502    }
02503    return AST_FEATURE_RETURN_SUCCESS;  /*! \todo XXX should probably return res */
02504 }
02505 
02506 static void unmap_features(void)
02507 {
02508    int x;
02509 
02510    ast_rwlock_wrlock(&features_lock);
02511    for (x = 0; x < FEATURES_COUNT; x++)
02512       strcpy(builtin_features[x].exten, builtin_features[x].default_exten);
02513    ast_rwlock_unlock(&features_lock);
02514 }
02515 
02516 static int remap_feature(const char *name, const char *value)
02517 {
02518    int x, res = -1;
02519 
02520    ast_rwlock_wrlock(&features_lock);
02521    for (x = 0; x < FEATURES_COUNT; x++) {
02522       if (strcasecmp(builtin_features[x].sname, name))
02523          continue;
02524 
02525       ast_copy_string(builtin_features[x].exten, value, sizeof(builtin_features[x].exten));
02526       res = 0;
02527       break;
02528    }
02529    ast_rwlock_unlock(&features_lock);
02530 
02531    return res;
02532 }
02533 
02534 /*!
02535  * \brief Helper function for feature_interpret and ast_feature_detect
02536  * \param chan,peer,config,code,sense,dynamic_features_buf,features,operation,feature
02537  *
02538  * Lock features list, browse for code, unlock list
02539  * If a feature is found and the operation variable is set, that feature's
02540  * operation is executed.  The first feature found is copied to the feature parameter.
02541  * \retval res on success.
02542  * \retval -1 on failure.
02543 */
02544 static int feature_interpret_helper(struct ast_channel *chan, struct ast_channel *peer,
02545    struct ast_bridge_config *config, const char *code, int sense, char *dynamic_features_buf,
02546    struct ast_flags *features, int operation, struct ast_call_feature *feature)
02547 {
02548    int x;
02549    struct feature_group *fg = NULL;
02550    struct feature_group_exten *fge;
02551    struct ast_call_feature *tmpfeature;
02552    char *tmp, *tok;
02553    int res = AST_FEATURE_RETURN_PASSDIGITS;
02554    int feature_detected = 0;
02555 
02556    if (!(peer && chan && config) && operation) {
02557       return -1; /* can not run feature operation */
02558    }
02559 
02560    ast_rwlock_rdlock(&features_lock);
02561    for (x = 0; x < FEATURES_COUNT; x++) {
02562       if ((ast_test_flag(features, builtin_features[x].feature_mask)) &&
02563           !ast_strlen_zero(builtin_features[x].exten)) {
02564          /* Feature is up for consideration */
02565          if (!strcmp(builtin_features[x].exten, code)) {
02566             ast_debug(3, "Feature detected: fname=%s sname=%s exten=%s\n", builtin_features[x].fname, builtin_features[x].sname, builtin_features[x].exten);
02567             if (operation) {
02568                res = builtin_features[x].operation(chan, peer, config, code, sense, NULL);
02569             }
02570             memcpy(feature, &builtin_features[x], sizeof(feature));
02571             feature_detected = 1;
02572             break;
02573          } else if (!strncmp(builtin_features[x].exten, code, strlen(code))) {
02574             if (res == AST_FEATURE_RETURN_PASSDIGITS)
02575                res = AST_FEATURE_RETURN_STOREDIGITS;
02576          }
02577       }
02578    }
02579    ast_rwlock_unlock(&features_lock);
02580 
02581    if (ast_strlen_zero(dynamic_features_buf) || feature_detected) {
02582       return res;
02583    }
02584 
02585    tmp = dynamic_features_buf;
02586 
02587    while ((tok = strsep(&tmp, "#"))) {
02588       AST_RWLIST_RDLOCK(&feature_groups);
02589 
02590       fg = find_group(tok);
02591 
02592       if (fg) {
02593          AST_LIST_TRAVERSE(&fg->features, fge, entry) {
02594             if (!strcmp(fge->exten, code)) {
02595                if (operation) {
02596                   res = fge->feature->operation(chan, peer, config, code, sense, fge->feature);
02597                }
02598                memcpy(feature, fge->feature, sizeof(feature));
02599                if (res != AST_FEATURE_RETURN_KEEPTRYING) {
02600                   AST_RWLIST_UNLOCK(&feature_groups);
02601                   break;
02602                }
02603                res = AST_FEATURE_RETURN_PASSDIGITS;
02604             } else if (!strncmp(fge->exten, code, strlen(code))) {
02605                res = AST_FEATURE_RETURN_STOREDIGITS;
02606             }
02607          }
02608          if (fge) {
02609             break;
02610          }
02611       }
02612 
02613       AST_RWLIST_UNLOCK(&feature_groups);
02614 
02615       AST_RWLIST_RDLOCK(&feature_list);
02616 
02617       if (!(tmpfeature = find_dynamic_feature(tok))) {
02618          AST_RWLIST_UNLOCK(&feature_list);
02619          continue;
02620       }
02621 
02622       /* Feature is up for consideration */
02623       if (!strcmp(tmpfeature->exten, code)) {
02624          ast_verb(3, " Feature Found: %s exten: %s\n",tmpfeature->sname, tok);
02625          if (operation) {
02626             res = tmpfeature->operation(chan, peer, config, code, sense, tmpfeature);
02627          }
02628          memcpy(feature, tmpfeature, sizeof(feature));
02629          if (res != AST_FEATURE_RETURN_KEEPTRYING) {
02630             AST_RWLIST_UNLOCK(&feature_list);
02631             break;
02632          }
02633          res = AST_FEATURE_RETURN_PASSDIGITS;
02634       } else if (!strncmp(tmpfeature->exten, code, strlen(code)))
02635          res = AST_FEATURE_RETURN_STOREDIGITS;
02636 
02637       AST_RWLIST_UNLOCK(&feature_list);
02638    }
02639 
02640    return res;
02641 }
02642 
02643 /*!
02644  * \brief Check the dynamic features
02645  * \param chan,peer,config,code,sense
02646  *
02647  * \retval res on success.
02648  * \retval -1 on failure.
02649 */
02650 
02651 static int feature_interpret(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense) {
02652 
02653    char dynamic_features_buf[128];
02654    const char *peer_dynamic_features, *chan_dynamic_features;
02655    struct ast_flags features;
02656    struct ast_call_feature feature;
02657    if (sense == FEATURE_SENSE_CHAN) {
02658       ast_copy_flags(&features, &(config->features_caller), AST_FLAGS_ALL);
02659    }
02660    else {
02661       ast_copy_flags(&features, &(config->features_callee), AST_FLAGS_ALL);
02662    }
02663 
02664    ast_channel_lock(peer);
02665    peer_dynamic_features = ast_strdupa(S_OR(pbx_builtin_getvar_helper(peer, "DYNAMIC_FEATURES"),""));
02666    ast_channel_unlock(peer);
02667 
02668    ast_channel_lock(chan);
02669    chan_dynamic_features = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES"),""));
02670    ast_channel_unlock(chan);
02671 
02672    snprintf(dynamic_features_buf, sizeof(dynamic_features_buf), "%s%s%s", S_OR(chan_dynamic_features, ""), chan_dynamic_features && peer_dynamic_features ? "#" : "", S_OR(peer_dynamic_features,""));
02673 
02674    ast_debug(3, "Feature interpret: chan=%s, peer=%s, code=%s, sense=%d, features=%d, dynamic=%s\n", chan->name, peer->name, code, sense, features.flags, dynamic_features_buf);
02675 
02676    return feature_interpret_helper(chan, peer, config, code, sense, dynamic_features_buf, &features, 1, &feature);
02677 }
02678 
02679 
02680 int ast_feature_detect(struct ast_channel *chan, struct ast_flags *features, const char *code, struct ast_call_feature *feature) {
02681 
02682    return feature_interpret_helper(chan, NULL, NULL, code, 0, NULL, features, 0, feature);
02683 }
02684 
02685 static void set_config_flags(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config)
02686 {
02687    int x;
02688 
02689    ast_clear_flag(config, AST_FLAGS_ALL);
02690 
02691    ast_rwlock_rdlock(&features_lock);
02692    for (x = 0; x < FEATURES_COUNT; x++) {
02693       if (!ast_test_flag(builtin_features + x, AST_FEATURE_FLAG_NEEDSDTMF))
02694          continue;
02695 
02696       if (ast_test_flag(&(config->features_caller), builtin_features[x].feature_mask))
02697          ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
02698 
02699       if (ast_test_flag(&(config->features_callee), builtin_features[x].feature_mask))
02700          ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
02701    }
02702    ast_rwlock_unlock(&features_lock);
02703 
02704    if (chan && peer && !(ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_0) && ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_1))) {
02705       const char *dynamic_features = pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES");
02706 
02707       if (dynamic_features) {
02708          char *tmp = ast_strdupa(dynamic_features);
02709          char *tok;
02710          struct ast_call_feature *feature;
02711 
02712          /* while we have a feature */
02713          while ((tok = strsep(&tmp, "#"))) {
02714             struct feature_group *fg;
02715 
02716             AST_RWLIST_RDLOCK(&feature_groups);
02717             AST_RWLIST_TRAVERSE(&feature_groups, fg, entry) {
02718                struct feature_group_exten *fge;
02719 
02720                AST_LIST_TRAVERSE(&fg->features, fge, entry) {
02721                   if (ast_test_flag(fge->feature, AST_FEATURE_FLAG_BYCALLER)) {
02722                      ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
02723                   }
02724                   if (ast_test_flag(fge->feature, AST_FEATURE_FLAG_BYCALLEE)) {
02725                      ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
02726                   }
02727                }
02728             }
02729             AST_RWLIST_UNLOCK(&feature_groups);
02730 
02731             AST_RWLIST_RDLOCK(&feature_list);
02732             if ((feature = find_dynamic_feature(tok)) && ast_test_flag(feature, AST_FEATURE_FLAG_NEEDSDTMF)) {
02733                if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER)) {
02734                   ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
02735                }
02736                if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE)) {
02737                   ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
02738                }
02739             }
02740             AST_RWLIST_UNLOCK(&feature_list);
02741          }
02742       }
02743    }
02744 }
02745 
02746 /*! 
02747  * \brief Get feature and dial
02748  * \param caller,transferee,type,format,data,timeout,outstate,cid_num,cid_name,igncallerstate,language
02749  *
02750  * Request channel, set channel variables, initiate call,check if they want to disconnect
02751  * go into loop, check if timeout has elapsed, check if person to be transfered hung up,
02752  * check for answer break loop, set cdr return channel.
02753  *
02754  * \todo XXX Check - this is very similar to the code in channel.c 
02755  * \return always a channel
02756 */
02757 static struct ast_channel *feature_request_and_dial(struct ast_channel *caller, struct ast_channel *transferee, const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name, int igncallerstate, const char *language)
02758 {
02759    int state = 0;
02760    int cause = 0;
02761    int to;
02762    struct ast_channel *chan;
02763    struct ast_channel *monitor_chans[2];
02764    struct ast_channel *active_channel;
02765    int res = 0, ready = 0;
02766    struct timeval started;
02767    int x, len = 0;
02768    char *disconnect_code = NULL, *dialed_code = NULL;
02769 
02770    if (!(chan = ast_request(type, format, caller, data, &cause))) {
02771       ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
02772       switch(cause) {
02773       case AST_CAUSE_BUSY:
02774          state = AST_CONTROL_BUSY;
02775          break;
02776       case AST_CAUSE_CONGESTION:
02777          state = AST_CONTROL_CONGESTION;
02778          break;
02779       }
02780       goto done;
02781    }
02782 
02783    ast_set_callerid(chan, cid_num, cid_name, cid_num);
02784    ast_string_field_set(chan, language, language);
02785    ast_channel_inherit_variables(caller, chan); 
02786    pbx_builtin_setvar_helper(chan, "TRANSFERERNAME", caller->name);
02787       
02788    ast_channel_lock(chan);
02789    ast_connected_line_copy_from_caller(&chan->connected, &caller->caller);
02790    ast_channel_unlock(chan);
02791    
02792    if (ast_call(chan, data, timeout)) {
02793       ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
02794       goto done;
02795    }
02796    
02797    ast_indicate(caller, AST_CONTROL_RINGING);
02798    /* support dialing of the featuremap disconnect code while performing an attended tranfer */
02799    ast_rwlock_rdlock(&features_lock);
02800    for (x = 0; x < FEATURES_COUNT; x++) {
02801       if (strcasecmp(builtin_features[x].sname, "disconnect"))
02802          continue;
02803 
02804       disconnect_code = builtin_features[x].exten;
02805       len = strlen(disconnect_code) + 1;
02806       dialed_code = alloca(len);
02807       memset(dialed_code, 0, len);
02808       break;
02809    }
02810    ast_rwlock_unlock(&features_lock);
02811    x = 0;
02812    started = ast_tvnow();
02813    to = timeout;
02814 
02815    ast_poll_channel_add(caller, chan);
02816 
02817    while (!((transferee && ast_check_hangup(transferee)) && (!igncallerstate && ast_check_hangup(caller))) && timeout && (chan->_state != AST_STATE_UP)) {
02818       struct ast_frame *f = NULL;
02819 
02820       monitor_chans[0] = caller;
02821       monitor_chans[1] = chan;
02822       active_channel = ast_waitfor_n(monitor_chans, 2, &to);
02823 
02824       /* see if the timeout has been violated */
02825       if(ast_tvdiff_ms(ast_tvnow(), started) > timeout) {
02826          state = AST_CONTROL_UNHOLD;
02827          ast_log(LOG_NOTICE, "We exceeded our AT-timeout\n");
02828          break; /*doh! timeout*/
02829       }
02830 
02831       if (!active_channel)
02832          continue;
02833 
02834       if (chan && (chan == active_channel)){
02835          if (!ast_strlen_zero(chan->call_forward)) {
02836             if (!(chan = ast_call_forward(caller, chan, NULL, format, NULL, outstate))) {
02837                return NULL;
02838             }
02839             continue;
02840          }
02841          f = ast_read(chan);
02842          if (f == NULL) { /*doh! where'd he go?*/
02843             state = AST_CONTROL_HANGUP;
02844             res = 0;
02845             break;
02846          }
02847          
02848          if (f->frametype == AST_FRAME_CONTROL || f->frametype == AST_FRAME_DTMF || f->frametype == AST_FRAME_TEXT) {
02849             if (f->subclass.integer == AST_CONTROL_RINGING) {
02850                state = f->subclass.integer;
02851                ast_verb(3, "%s is ringing\n", chan->name);
02852                ast_indicate(caller, AST_CONTROL_RINGING);
02853             } else if ((f->subclass.integer == AST_CONTROL_BUSY) || (f->subclass.integer == AST_CONTROL_CONGESTION)) {
02854                state = f->subclass.integer;
02855                ast_verb(3, "%s is busy\n", chan->name);
02856                ast_indicate(caller, AST_CONTROL_BUSY);
02857                ast_frfree(f);
02858                f = NULL;
02859                break;
02860             } else if (f->subclass.integer == AST_CONTROL_ANSWER) {
02861                /* This is what we are hoping for */
02862                state = f->subclass.integer;
02863                ast_frfree(f);
02864                f = NULL;
02865                ready=1;
02866                break;
02867             } else if (f->subclass.integer == AST_CONTROL_CONNECTED_LINE) {
02868                if (ast_channel_connected_line_macro(chan, caller, f, 1, 1)) {
02869                   ast_indicate_data(caller, AST_CONTROL_CONNECTED_LINE, f->data.ptr, f->datalen);
02870                }
02871             } else if (f->subclass.integer == AST_CONTROL_REDIRECTING) {
02872                if (ast_channel_redirecting_macro(chan, caller, f, 1, 1)) {
02873                   ast_indicate_data(caller, AST_CONTROL_REDIRECTING, f->data.ptr, f->datalen);
02874                }
02875             } else if (f->subclass.integer != -1 && f->subclass.integer != AST_CONTROL_PROGRESS) {
02876                ast_log(LOG_NOTICE, "Don't know what to do about control frame: %d\n", f->subclass.integer);
02877             }
02878             /* else who cares */
02879          } else if (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO) {
02880             ast_write(caller, f);
02881          }
02882 
02883       } else if (caller && (active_channel == caller)) {
02884          f = ast_read(caller);
02885          if (f == NULL) { /*doh! where'd he go?*/
02886             if (!igncallerstate) {
02887                if (ast_check_hangup(caller) && !ast_check_hangup(chan)) {
02888                   /* make this a blind transfer */
02889                   ready = 1;
02890                   break;
02891                }
02892                state = AST_CONTROL_HANGUP;
02893                res = 0;
02894                break;
02895             }
02896          } else {
02897          
02898             if (f->frametype == AST_FRAME_DTMF) {
02899                dialed_code[x++] = f->subclass.integer;
02900                dialed_code[x] = '\0';
02901                if (strlen(dialed_code) == len) {
02902                   x = 0;
02903                } else if (x && strncmp(dialed_code, disconnect_code, x)) {
02904                   x = 0;
02905                   dialed_code[x] = '\0';
02906                }
02907                if (*dialed_code && !strcmp(dialed_code, disconnect_code)) {
02908                   /* Caller Canceled the call */
02909                   state = AST_CONTROL_UNHOLD;
02910                   ast_frfree(f);
02911                   f = NULL;
02912                   break;
02913                }
02914             } else if (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO) {
02915                ast_write(chan, f);
02916             }
02917          }
02918       }
02919       if (f)
02920          ast_frfree(f);
02921    } /* end while */
02922 
02923    ast_poll_channel_del(caller, chan);
02924       
02925 done:
02926    ast_indicate(caller, -1);
02927    if (chan && ready) {
02928       if (chan->_state == AST_STATE_UP) 
02929          state = AST_CONTROL_ANSWER;
02930       res = 0;
02931    } else if (chan) {
02932       res = -1;
02933       ast_hangup(chan);
02934       chan = NULL;
02935    } else {
02936       res = -1;
02937    }
02938    
02939    if (outstate)
02940       *outstate = state;
02941 
02942    return chan;
02943 }
02944 
02945 void ast_channel_log(char *title, struct ast_channel *chan);
02946 
02947 void ast_channel_log(char *title, struct ast_channel *chan) /* for debug, this is handy enough to justify keeping it in the source */
02948 {
02949        ast_log(LOG_NOTICE, "______ %s (%lx)______\n", title, (unsigned long)chan);
02950        ast_log(LOG_NOTICE, "CHAN: name: %s;  appl: %s; data: %s; contxt: %s;  exten: %s; pri: %d;\n",
02951                        chan->name, chan->appl, chan->data, chan->context, chan->exten, chan->priority);
02952        ast_log(LOG_NOTICE, "CHAN: acctcode: %s;  dialcontext: %s; amaflags: %x; maccontxt: %s;  macexten: %s; macpri: %d;\n",
02953                        chan->accountcode, chan->dialcontext, chan->amaflags, chan->macrocontext, chan->macroexten, chan->macropriority);
02954        ast_log(LOG_NOTICE, "CHAN: masq: %p;  masqr: %p; _bridge: %p; uniqueID: %s; linkedID:%s\n",
02955                        chan->masq, chan->masqr,
02956                        chan->_bridge, chan->uniqueid, chan->linkedid);
02957        if (chan->masqr)
02958                ast_log(LOG_NOTICE, "CHAN: masquerading as: %s;  cdr: %p;\n",
02959                                chan->masqr->name, chan->masqr->cdr);
02960        if (chan->_bridge)
02961                ast_log(LOG_NOTICE, "CHAN: Bridged to %s\n", chan->_bridge->name);
02962 
02963    ast_log(LOG_NOTICE, "===== done ====\n");
02964 }
02965 
02966 /*!
02967  * \brief return the first unlocked cdr in a possible chain
02968 */
02969 static struct ast_cdr *pick_unlocked_cdr(struct ast_cdr *cdr)
02970 {
02971    struct ast_cdr *cdr_orig = cdr;
02972    while (cdr) {
02973       if (!ast_test_flag(cdr,AST_CDR_FLAG_LOCKED))
02974          return cdr;
02975       cdr = cdr->next;
02976    }
02977    return cdr_orig; /* everybody LOCKED or some other weirdness, like a NULL */
02978 }
02979 
02980 static void set_bridge_features_on_config(struct ast_bridge_config *config, const char *features)
02981 {
02982    const char *feature;
02983 
02984    if (ast_strlen_zero(features)) {
02985       return;
02986    }
02987 
02988    for (feature = features; *feature; feature++) {
02989       switch (*feature) {
02990       case 'T' :
02991       case 't' :
02992          ast_set_flag(&(config->features_caller), AST_FEATURE_REDIRECT);
02993          break;
02994       case 'K' :
02995       case 'k' :
02996          ast_set_flag(&(config->features_caller), AST_FEATURE_PARKCALL);
02997          break;
02998       case 'H' :
02999       case 'h' :
03000          ast_set_flag(&(config->features_caller), AST_FEATURE_DISCONNECT);
03001          break;
03002       case 'W' :
03003       case 'w' :
03004          ast_set_flag(&(config->features_caller), AST_FEATURE_AUTOMON);
03005          break;
03006       default :
03007          ast_log(LOG_WARNING, "Skipping unknown feature code '%c'\n", *feature);
03008       }
03009    }
03010 }
03011 
03012 static void add_features_datastores(struct ast_channel *caller, struct ast_channel *callee, struct ast_bridge_config *config)
03013 {
03014    struct ast_datastore *ds_callee_features = NULL, *ds_caller_features = NULL;
03015    struct ast_dial_features *callee_features = NULL, *caller_features = NULL;
03016 
03017    ast_channel_lock(caller);
03018    ds_caller_features = ast_channel_datastore_find(caller, &dial_features_info, NULL);
03019    ast_channel_unlock(caller);
03020    if (!ds_caller_features) {
03021       if (!(ds_caller_features = ast_datastore_alloc(&dial_features_info, NULL))) {
03022          ast_log(LOG_WARNING, "Unable to create channel datastore for caller features. Aborting!\n");
03023          return;
03024       }
03025       if (!(caller_features = ast_calloc(1, sizeof(*caller_features)))) {
03026          ast_log(LOG_WARNING, "Unable to allocate memory for callee feature flags. Aborting!\n");
03027          ast_datastore_free(ds_caller_features);
03028          return;
03029       }
03030       ds_caller_features->inheritance = DATASTORE_INHERIT_FOREVER;
03031       caller_features->is_caller = 1;
03032       ast_copy_flags(&(caller_features->features_callee), &(config->features_callee), AST_FLAGS_ALL);
03033       ast_copy_flags(&(caller_features->features_caller), &(config->features_caller), AST_FLAGS_ALL);
03034       ds_caller_features->data = caller_features;
03035       ast_channel_lock(caller);
03036       ast_channel_datastore_add(caller, ds_caller_features);
03037       ast_channel_unlock(caller);
03038    } else {
03039       /* If we don't return here, then when we do a builtin_atxfer we will copy the disconnect
03040        * flags over from the atxfer to the caller */
03041       return;
03042    }
03043 
03044    ast_channel_lock(callee);
03045    ds_callee_features = ast_channel_datastore_find(callee, &dial_features_info, NULL);
03046    ast_channel_unlock(callee);
03047    if (!ds_callee_features) {
03048       if (!(ds_callee_features = ast_datastore_alloc(&dial_features_info, NULL))) {
03049          ast_log(LOG_WARNING, "Unable to create channel datastore for callee features. Aborting!\n");
03050          return;
03051       }
03052       if (!(callee_features = ast_calloc(1, sizeof(*callee_features)))) {
03053          ast_log(LOG_WARNING, "Unable to allocate memory for callee feature flags. Aborting!\n");
03054          ast_datastore_free(ds_callee_features);
03055          return;
03056       }
03057       ds_callee_features->inheritance = DATASTORE_INHERIT_FOREVER;
03058       callee_features->is_caller = 0;
03059       ast_copy_flags(&(callee_features->features_callee), &(config->features_caller), AST_FLAGS_ALL);
03060       ast_copy_flags(&(callee_features->features_caller), &(config->features_callee), AST_FLAGS_ALL);
03061       ds_callee_features->data = callee_features;
03062       ast_channel_lock(callee);
03063       ast_channel_datastore_add(callee, ds_callee_features);
03064       ast_channel_unlock(callee);
03065    }
03066 
03067    return;
03068 }
03069 
03070 /*!
03071  * \brief bridge the call and set CDR
03072  * \param chan,peer,config
03073  * 
03074  * Set start time, check for two channels,check if monitor on
03075  * check for feature activation, create new CDR
03076  * \retval res on success.
03077  * \retval -1 on failure to bridge.
03078 */
03079 int ast_bridge_call(struct ast_channel *chan,struct ast_channel *peer,struct ast_bridge_config *config)
03080 {
03081    /* Copy voice back and forth between the two channels.  Give the peer
03082       the ability to transfer calls with '#<extension' syntax. */
03083    struct ast_frame *f;
03084    struct ast_channel *who;
03085    char chan_featurecode[FEATURE_MAX_LEN + 1]="";
03086    char peer_featurecode[FEATURE_MAX_LEN + 1]="";
03087    char orig_channame[AST_MAX_EXTENSION];
03088    char orig_peername[AST_MAX_EXTENSION];
03089    int res;
03090    int diff;
03091    int hasfeatures=0;
03092    int hadfeatures=0;
03093    int autoloopflag;
03094    struct ast_option_header *aoh;
03095    struct ast_cdr *bridge_cdr = NULL;
03096    struct ast_cdr *orig_peer_cdr = NULL;
03097    struct ast_cdr *chan_cdr = chan->cdr; /* the proper chan cdr, if there are forked cdrs */
03098    struct ast_cdr *peer_cdr = peer->cdr; /* the proper chan cdr, if there are forked cdrs */
03099    struct ast_cdr *new_chan_cdr = NULL; /* the proper chan cdr, if there are forked cdrs */
03100    struct ast_cdr *new_peer_cdr = NULL; /* the proper chan cdr, if there are forked cdrs */
03101 
03102    if (chan && peer) {
03103       pbx_builtin_setvar_helper(chan, "BRIDGEPEER", peer->name);
03104       pbx_builtin_setvar_helper(peer, "BRIDGEPEER", chan->name);
03105    } else if (chan) {
03106       pbx_builtin_setvar_helper(chan, "BLINDTRANSFER", NULL);
03107    }
03108 
03109    set_bridge_features_on_config(config, pbx_builtin_getvar_helper(chan, "BRIDGE_FEATURES"));
03110    add_features_datastores(chan, peer, config);
03111 
03112    /* This is an interesting case.  One example is if a ringing channel gets redirected to
03113     * an extension that picks up a parked call.  This will make sure that the call taken
03114     * out of parking gets told that the channel it just got bridged to is still ringing. */
03115    if (chan->_state == AST_STATE_RINGING && peer->visible_indication != AST_CONTROL_RINGING) {
03116       ast_indicate(peer, AST_CONTROL_RINGING);
03117    }
03118 
03119    if (monitor_ok) {
03120       const char *monitor_exec;
03121       struct ast_channel *src = NULL;
03122       if (!monitor_app) {
03123          if (!(monitor_app = pbx_findapp("Monitor")))
03124             monitor_ok=0;
03125       }
03126       if ((monitor_exec = pbx_builtin_getvar_helper(chan, "AUTO_MONITOR"))) 
03127          src = chan;
03128       else if ((monitor_exec = pbx_builtin_getvar_helper(peer, "AUTO_MONITOR")))
03129          src = peer;
03130       if (monitor_app && src) {
03131          char *tmp = ast_strdupa(monitor_exec);
03132          pbx_exec(src, monitor_app, tmp);
03133       }
03134    }
03135 
03136    set_config_flags(chan, peer, config);
03137 
03138    /* Answer if need be */
03139    if (chan->_state != AST_STATE_UP) {
03140       if (ast_raw_answer(chan, 1)) {
03141          return -1;
03142       }
03143    }
03144 
03145 #ifdef FOR_DEBUG
03146    /* show the two channels and cdrs involved in the bridge for debug & devel purposes */
03147    ast_channel_log("Pre-bridge CHAN Channel info", chan);
03148    ast_channel_log("Pre-bridge PEER Channel info", peer);
03149 #endif
03150    /* two channels are being marked as linked here */
03151    ast_channel_set_linkgroup(chan,peer);
03152 
03153    /* copy the userfield from the B-leg to A-leg if applicable */
03154    if (chan->cdr && peer->cdr && !ast_strlen_zero(peer->cdr->userfield)) {
03155       char tmp[256];
03156       if (!ast_strlen_zero(chan->cdr->userfield)) {
03157          snprintf(tmp, sizeof(tmp), "%s;%s", chan->cdr->userfield, peer->cdr->userfield);
03158          ast_cdr_appenduserfield(chan, tmp);
03159       } else
03160          ast_cdr_setuserfield(chan, peer->cdr->userfield);
03161       /* free the peer's cdr without ast_cdr_free complaining */
03162       ast_free(peer->cdr);
03163       peer->cdr = NULL;
03164    }
03165    ast_copy_string(orig_channame,chan->name,sizeof(orig_channame));
03166    ast_copy_string(orig_peername,peer->name,sizeof(orig_peername));
03167    orig_peer_cdr = peer_cdr;
03168    
03169    if (!chan_cdr || (chan_cdr && !ast_test_flag(chan_cdr, AST_CDR_FLAG_POST_DISABLED))) {
03170       
03171       if (chan_cdr) {
03172          ast_set_flag(chan_cdr, AST_CDR_FLAG_MAIN);
03173          ast_cdr_update(chan);
03174          bridge_cdr = ast_cdr_dup_unique_swap(chan_cdr);
03175          /* rip any forked CDR's off of the chan_cdr and attach
03176           * them to the bridge_cdr instead */
03177          bridge_cdr->next = chan_cdr->next;
03178          chan_cdr->next = NULL;
03179          ast_copy_string(bridge_cdr->lastapp, S_OR(chan->appl, ""), sizeof(bridge_cdr->lastapp));
03180          ast_copy_string(bridge_cdr->lastdata, S_OR(chan->data, ""), sizeof(bridge_cdr->lastdata));
03181          if (peer_cdr && !ast_strlen_zero(peer_cdr->userfield)) {
03182             ast_copy_string(bridge_cdr->userfield, peer_cdr->userfield, sizeof(bridge_cdr->userfield));
03183          }
03184          ast_cdr_setaccount(peer, chan->accountcode);
03185 
03186       } else {
03187          /* better yet, in a xfer situation, find out why the chan cdr got zapped (pun unintentional) */
03188          bridge_cdr = ast_cdr_alloc(); /* this should be really, really rare/impossible? */
03189          ast_copy_string(bridge_cdr->channel, chan->name, sizeof(bridge_cdr->channel));
03190          ast_copy_string(bridge_cdr->dstchannel, peer->name, sizeof(bridge_cdr->dstchannel));
03191          ast_copy_string(bridge_cdr->uniqueid, chan->uniqueid, sizeof(bridge_cdr->uniqueid));
03192          ast_copy_string(bridge_cdr->lastapp, S_OR(chan->appl, ""), sizeof(bridge_cdr->lastapp));
03193          ast_copy_string(bridge_cdr->lastdata, S_OR(chan->data, ""), sizeof(bridge_cdr->lastdata));
03194          ast_cdr_setcid(bridge_cdr, chan);
03195          bridge_cdr->disposition = (chan->_state == AST_STATE_UP) ?  AST_CDR_ANSWERED : AST_CDR_NULL;
03196          bridge_cdr->amaflags = chan->amaflags ? chan->amaflags :  ast_default_amaflags;
03197          ast_copy_string(bridge_cdr->accountcode, chan->accountcode, sizeof(bridge_cdr->accountcode));
03198          /* Destination information */
03199          ast_copy_string(bridge_cdr->dst, chan->exten, sizeof(bridge_cdr->dst));
03200          ast_copy_string(bridge_cdr->dcontext, chan->context, sizeof(bridge_cdr->dcontext));
03201          if (peer_cdr) {
03202             bridge_cdr->start = peer_cdr->start;
03203             ast_copy_string(bridge_cdr->userfield, peer_cdr->userfield, sizeof(bridge_cdr->userfield));
03204          } else {
03205             ast_cdr_start(bridge_cdr);
03206          }
03207       }
03208       ast_debug(4,"bridge answer set, chan answer set\n");
03209       /* peer_cdr->answer will be set when a macro runs on the peer;
03210          in that case, the bridge answer will be delayed while the
03211          macro plays on the peer channel. The peer answered the call
03212          before the macro started playing. To the phone system,
03213          this is billable time for the call, even tho the caller
03214          hears nothing but ringing while the macro does its thing. */
03215 
03216       /* Another case where the peer cdr's time will be set, is when
03217          A self-parks by pickup up phone and dialing 700, then B
03218          picks up A by dialing its parking slot; there may be more 
03219          practical paths that get the same result, tho... in which
03220          case you get the previous answer time from the Park... which
03221          is before the bridge's start time, so I added in the 
03222          tvcmp check to the if below */
03223 
03224       if (peer_cdr && !ast_tvzero(peer_cdr->answer) && ast_tvcmp(peer_cdr->answer, bridge_cdr->start) >= 0) {
03225          ast_cdr_setanswer(bridge_cdr, peer_cdr->answer);
03226          ast_cdr_setdisposition(bridge_cdr, peer_cdr->disposition);
03227          if (chan_cdr) {
03228             ast_cdr_setanswer(chan_cdr, peer_cdr->answer);
03229             ast_cdr_setdisposition(chan_cdr, peer_cdr->disposition);
03230          }
03231       } else {
03232          ast_cdr_answer(bridge_cdr);
03233          if (chan_cdr) {
03234             ast_cdr_answer(chan_cdr); /* for the sake of cli status checks */
03235          }
03236       }
03237       if (ast_test_flag(chan,AST_FLAG_BRIDGE_HANGUP_DONT) && (chan_cdr || peer_cdr)) {
03238          if (chan_cdr) {
03239             ast_set_flag(chan_cdr, AST_CDR_FLAG_BRIDGED);
03240          }
03241          if (peer_cdr) {
03242             ast_set_flag(peer_cdr, AST_CDR_FLAG_BRIDGED);
03243          }
03244       }
03245       /* the DIALED flag may be set if a dialed channel is transfered
03246        * and then bridged to another channel.  In order for the
03247        * bridge CDR to be written, the DIALED flag must not be
03248        * present. */
03249       ast_clear_flag(bridge_cdr, AST_CDR_FLAG_DIALED);
03250    }
03251    ast_cel_report_event(chan, AST_CEL_BRIDGE_START, NULL, NULL, NULL);
03252    for (;;) {
03253       struct ast_channel *other; /* used later */
03254    
03255       res = ast_channel_bridge(chan, peer, config, &f, &who);
03256       
03257       /* When frame is not set, we are probably involved in a situation
03258          where we've timed out.
03259          When frame is set, we'll come this code twice; once for DTMF_BEGIN
03260          and also for DTMF_END. If we flow into the following 'if' for both, then 
03261          our wait times are cut in half, as both will subtract from the
03262          feature_timer. Not good!
03263       */
03264       if (config->feature_timer && (!f || f->frametype == AST_FRAME_DTMF_END)) {
03265          /* Update feature timer for next pass */
03266          diff = ast_tvdiff_ms(ast_tvnow(), config->feature_start_time);
03267          if (res == AST_BRIDGE_RETRY) {
03268             /* The feature fully timed out but has not been updated. Skip
03269              * the potential round error from the diff calculation and
03270              * explicitly set to expired. */
03271             config->feature_timer = -1;
03272          } else {
03273             config->feature_timer -= diff;
03274          }
03275 
03276          if (hasfeatures) {
03277             if (config->feature_timer <= 0) {
03278                /* Not *really* out of time, just out of time for
03279                   digits to come in for features. */
03280                ast_debug(1, "Timed out for feature!\n");
03281                if (!ast_strlen_zero(peer_featurecode)) {
03282                   ast_dtmf_stream(chan, peer, peer_featurecode, 0, 0);
03283                   memset(peer_featurecode, 0, sizeof(peer_featurecode));
03284                }
03285                if (!ast_strlen_zero(chan_featurecode)) {
03286                   ast_dtmf_stream(peer, chan, chan_featurecode, 0, 0);
03287                   memset(chan_featurecode, 0, sizeof(chan_featurecode));
03288                }
03289                if (f)
03290                   ast_frfree(f);
03291                hasfeatures = !ast_strlen_zero(chan_featurecode) || !ast_strlen_zero(peer_featurecode);
03292                if (!hasfeatures) {
03293                   /* No more digits expected - reset the timer */
03294                   config->feature_timer = 0;
03295                }
03296                hadfeatures = hasfeatures;
03297                /* Continue as we were */
03298                continue;
03299             } else if (!f) {
03300                /* The bridge returned without a frame and there is a feature in progress.
03301                 * However, we don't think the feature has quite yet timed out, so just
03302                 * go back into the bridge. */
03303                continue;
03304             }
03305          } else {
03306             if (config->feature_timer <=0) {
03307                /* We ran out of time */
03308                config->feature_timer = 0;
03309                who = chan;
03310                if (f)
03311                   ast_frfree(f);
03312                f = NULL;
03313                res = 0;
03314             }
03315          }
03316       }
03317       if (res < 0) {
03318          if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_test_flag(peer, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan) && !ast_check_hangup(peer)) {
03319             ast_log(LOG_WARNING, "Bridge failed on channels %s and %s\n", chan->name, peer->name);
03320          }
03321          goto before_you_go;
03322       }
03323       
03324       if (!f || (f->frametype == AST_FRAME_CONTROL &&
03325             (f->subclass.integer == AST_CONTROL_HANGUP || f->subclass.integer == AST_CONTROL_BUSY ||
03326                f->subclass.integer == AST_CONTROL_CONGESTION))) {
03327          res = -1;
03328          break;
03329       }
03330       /* many things should be sent to the 'other' channel */
03331       other = (who == chan) ? peer : chan;
03332       if (f->frametype == AST_FRAME_CONTROL) {
03333          switch (f->subclass.integer) {
03334          case AST_CONTROL_RINGING:
03335          case AST_CONTROL_FLASH:
03336          case -1:
03337             ast_indicate(other, f->subclass.integer);
03338             break;
03339          case AST_CONTROL_CONNECTED_LINE:
03340             if (!ast_channel_connected_line_macro(who, other, f, who != chan, 1)) {
03341                break;
03342             }
03343             ast_indicate_data(other, f->subclass.integer, f->data.ptr, f->datalen);
03344             break;
03345          case AST_CONTROL_REDIRECTING:
03346             if (!ast_channel_redirecting_macro(who, other, f, who != chan, 1)) {
03347                break;
03348             }
03349             ast_indicate_data(other, f->subclass.integer, f->data.ptr, f->datalen);
03350             break;
03351          case AST_CONTROL_AOC:
03352          case AST_CONTROL_HOLD:
03353          case AST_CONTROL_UNHOLD:
03354             ast_indicate_data(other, f->subclass.integer, f->data.ptr, f->datalen);
03355             break;
03356          case AST_CONTROL_OPTION:
03357             aoh = f->data.ptr;
03358             /* Forward option Requests */
03359             if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
03360                ast_channel_setoption(other, ntohs(aoh->option), aoh->data, 
03361                   f->datalen - sizeof(struct ast_option_header), 0);
03362             }
03363             break;
03364          }
03365       } else if (f->frametype == AST_FRAME_DTMF_BEGIN) {
03366          /* eat it */
03367       } else if (f->frametype == AST_FRAME_DTMF) {
03368          char *featurecode;
03369          int sense;
03370 
03371          hadfeatures = hasfeatures;
03372          /* This cannot overrun because the longest feature is one shorter than our buffer */
03373          if (who == chan) {
03374             sense = FEATURE_SENSE_CHAN;
03375             featurecode = chan_featurecode;
03376          } else  {
03377             sense = FEATURE_SENSE_PEER;
03378             featurecode = peer_featurecode;
03379          }
03380          /*! append the event to featurecode. we rely on the string being zero-filled, and
03381           * not overflowing it. 
03382           * \todo XXX how do we guarantee the latter ?
03383           */
03384          featurecode[strlen(featurecode)] = f->subclass.integer;
03385          /* Get rid of the frame before we start doing "stuff" with the channels */
03386          ast_frfree(f);
03387          f = NULL;
03388          config->feature_timer = 0;
03389          res = feature_interpret(chan, peer, config, featurecode, sense);
03390          switch(res) {
03391          case AST_FEATURE_RETURN_PASSDIGITS:
03392             ast_dtmf_stream(other, who, featurecode, 0, 0);
03393             /* Fall through */
03394          case AST_FEATURE_RETURN_SUCCESS:
03395             memset(featurecode, 0, sizeof(chan_featurecode));
03396             break;
03397          }
03398          if (res >= AST_FEATURE_RETURN_PASSDIGITS) {
03399             res = 0;
03400          } else {
03401             break;
03402          }
03403          hasfeatures = !ast_strlen_zero(chan_featurecode) || !ast_strlen_zero(peer_featurecode);
03404          if (hadfeatures && !hasfeatures) {
03405             /* Feature completed or timed out */
03406             config->feature_timer = 0;
03407          } else if (hasfeatures) {
03408             if (config->timelimit) {
03409                /* No warning next time - we are waiting for future */
03410                ast_set_flag(config, AST_FEATURE_WARNING_ACTIVE);
03411             }
03412             config->feature_start_time = ast_tvnow();
03413             config->feature_timer = featuredigittimeout;
03414             ast_debug(1, "Set feature timer to %ld\n", config->feature_timer);
03415          }
03416       }
03417       if (f)
03418          ast_frfree(f);
03419 
03420    }
03421    ast_cel_report_event(chan, AST_CEL_BRIDGE_END, NULL, NULL, NULL);
03422    before_you_go:
03423 
03424    if (ast_test_flag(chan,AST_FLAG_BRIDGE_HANGUP_DONT)) {
03425       ast_clear_flag(chan,AST_FLAG_BRIDGE_HANGUP_DONT); /* its job is done */
03426       if (bridge_cdr) {
03427          ast_cdr_discard(bridge_cdr);
03428          /* QUESTION: should we copy bridge_cdr fields to the peer before we throw it away? */
03429       }
03430       return res; /* if we shouldn't do the h-exten, we shouldn't do the bridge cdr, either! */
03431    }
03432 
03433    if (config->end_bridge_callback) {
03434       config->end_bridge_callback(config->end_bridge_callback_data);
03435    }
03436 
03437    /* run the hangup exten on the chan object IFF it was NOT involved in a parking situation 
03438     * if it were, then chan belongs to a different thread now, and might have been hung up long
03439      * ago.
03440     */
03441    if (!ast_test_flag(&(config->features_caller),AST_FEATURE_NO_H_EXTEN)
03442       && ast_exists_extension(chan, chan->context, "h", 1,
03443          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
03444       struct ast_cdr *swapper = NULL;
03445       char savelastapp[AST_MAX_EXTENSION];
03446       char savelastdata[AST_MAX_EXTENSION];
03447       char save_exten[AST_MAX_EXTENSION];
03448       int  save_prio;
03449       int  found = 0;   /* set if we find at least one match */
03450       int  spawn_error = 0;
03451       
03452       autoloopflag = ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP);
03453       ast_set_flag(chan, AST_FLAG_IN_AUTOLOOP);
03454       if (bridge_cdr && ast_opt_end_cdr_before_h_exten) {
03455          ast_cdr_end(bridge_cdr);
03456       }
03457       /* swap the bridge cdr and the chan cdr for a moment, and let the endbridge
03458          dialplan code operate on it */
03459       ast_channel_lock(chan);
03460       if (bridge_cdr) {
03461          swapper = chan->cdr;
03462          ast_copy_string(savelastapp, bridge_cdr->lastapp, sizeof(bridge_cdr->lastapp));
03463          ast_copy_string(savelastdata, bridge_cdr->lastdata, sizeof(bridge_cdr->lastdata));
03464          chan->cdr = bridge_cdr;
03465       }
03466       ast_copy_string(save_exten, chan->exten, sizeof(save_exten));
03467       save_prio = chan->priority;
03468       ast_copy_string(chan->exten, "h", sizeof(chan->exten));
03469       chan->priority = 1;
03470       ast_channel_unlock(chan);
03471       while ((spawn_error = ast_spawn_extension(chan, chan->context, chan->exten,
03472          chan->priority,
03473          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL),
03474          &found, 1)) == 0) {
03475          chan->priority++;
03476       }
03477       if (spawn_error
03478          && (!ast_exists_extension(chan, chan->context, chan->exten, chan->priority,
03479             S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))
03480             || ast_check_hangup(chan))) {
03481          /* if the extension doesn't exist or a hangup occurred, this isn't really a spawn error */
03482          spawn_error = 0;
03483       }
03484       if (found && spawn_error) {
03485          /* Something bad happened, or a hangup has been requested. */
03486          ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", chan->context, chan->exten, chan->priority, chan->name);
03487          ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", chan->context, chan->exten, chan->priority, chan->name);
03488       }
03489       /* swap it back */
03490       ast_channel_lock(chan);
03491       ast_copy_string(chan->exten, save_exten, sizeof(chan->exten));
03492       chan->priority = save_prio;
03493       if (bridge_cdr) {
03494          if (chan->cdr == bridge_cdr) {
03495             chan->cdr = swapper;
03496          } else {
03497             bridge_cdr = NULL;
03498          }
03499       }
03500       if (!spawn_error) {
03501          ast_set_flag(chan, AST_FLAG_BRIDGE_HANGUP_RUN);
03502       }
03503       ast_channel_unlock(chan);
03504       /* protect the lastapp/lastdata against the effects of the hangup/dialplan code */
03505       if (bridge_cdr) {
03506          ast_copy_string(bridge_cdr->lastapp, savelastapp, sizeof(bridge_cdr->lastapp));
03507          ast_copy_string(bridge_cdr->lastdata, savelastdata, sizeof(bridge_cdr->lastdata));
03508       }
03509       ast_set2_flag(chan, autoloopflag, AST_FLAG_IN_AUTOLOOP);
03510    }
03511    
03512    /* obey the NoCDR() wishes. -- move the DISABLED flag to the bridge CDR if it was set on the channel during the bridge... */
03513    new_chan_cdr = pick_unlocked_cdr(chan->cdr); /* the proper chan cdr, if there are forked cdrs */
03514    if (bridge_cdr && new_chan_cdr && ast_test_flag(new_chan_cdr, AST_CDR_FLAG_POST_DISABLED))
03515       ast_set_flag(bridge_cdr, AST_CDR_FLAG_POST_DISABLED);
03516 
03517    /* we can post the bridge CDR at this point */
03518    if (bridge_cdr) {
03519       ast_cdr_end(bridge_cdr);
03520       ast_cdr_detach(bridge_cdr);
03521    }
03522    
03523    /* do a specialized reset on the beginning channel
03524       CDR's, if they still exist, so as not to mess up
03525       issues in future bridges;
03526       
03527       Here are the rules of the game:
03528       1. The chan and peer channel pointers will not change
03529          during the life of the bridge.
03530       2. But, in transfers, the channel names will change.
03531          between the time the bridge is started, and the
03532          time the channel ends. 
03533          Usually, when a channel changes names, it will
03534          also change CDR pointers.
03535       3. Usually, only one of the two channels (chan or peer)
03536          will change names.
03537       4. Usually, if a channel changes names during a bridge,
03538          it is because of a transfer. Usually, in these situations,
03539          it is normal to see 2 bridges running simultaneously, and
03540          it is not unusual to see the two channels that change
03541          swapped between bridges.
03542       5. After a bridge occurs, we have 2 or 3 channels' CDRs
03543          to attend to; if the chan or peer changed names,
03544          we have the before and after attached CDR's.
03545    */
03546 
03547    if (new_chan_cdr) {
03548       struct ast_channel *chan_ptr = NULL;
03549 
03550       if (strcasecmp(orig_channame, chan->name) != 0) { 
03551          /* old channel */
03552          if ((chan_ptr = ast_channel_get_by_name(orig_channame))) {
03553             ast_channel_lock(chan_ptr);
03554             if (!ast_bridged_channel(chan_ptr)) {
03555                struct ast_cdr *cur;
03556                for (cur = chan_ptr->cdr; cur; cur = cur->next) {
03557                   if (cur == chan_cdr) {
03558                      break;
03559                   }
03560                }
03561                if (cur) {
03562                   ast_cdr_specialized_reset(chan_cdr, 0);
03563                }
03564             }
03565             ast_channel_unlock(chan_ptr);
03566             chan_ptr = ast_channel_unref(chan_ptr);
03567          }
03568          /* new channel */
03569          ast_cdr_specialized_reset(new_chan_cdr, 0);
03570       } else {
03571          ast_cdr_specialized_reset(chan->cdr, 0); /* nothing changed, reset the chan cdr  */
03572       }
03573    }
03574 
03575    {
03576       struct ast_channel *chan_ptr = NULL;
03577       new_peer_cdr = pick_unlocked_cdr(peer->cdr); /* the proper chan cdr, if there are forked cdrs */
03578       if (new_chan_cdr && ast_test_flag(new_chan_cdr, AST_CDR_FLAG_POST_DISABLED) && new_peer_cdr && !ast_test_flag(new_peer_cdr, AST_CDR_FLAG_POST_DISABLED))
03579          ast_set_flag(new_peer_cdr, AST_CDR_FLAG_POST_DISABLED); /* DISABLED is viral-- it will propagate across a bridge */
03580       if (strcasecmp(orig_peername, peer->name) != 0) { 
03581          /* old channel */
03582          if ((chan_ptr = ast_channel_get_by_name(orig_peername))) {
03583             ast_channel_lock(chan_ptr);
03584             if (!ast_bridged_channel(chan_ptr)) {
03585                struct ast_cdr *cur;
03586                for (cur = chan_ptr->cdr; cur; cur = cur->next) {
03587                   if (cur == peer_cdr) {
03588                      break;
03589                   }
03590                }
03591                if (cur) {
03592                   ast_cdr_specialized_reset(peer_cdr, 0);
03593                }
03594             }
03595             ast_channel_unlock(chan_ptr);
03596             chan_ptr = ast_channel_unref(chan_ptr);
03597          }
03598          /* new channel */
03599          if (new_peer_cdr) {
03600             ast_cdr_specialized_reset(new_peer_cdr, 0);
03601          }
03602       } else {
03603          ast_cdr_specialized_reset(peer->cdr, 0); /* nothing changed, reset the peer cdr  */
03604       }
03605    }
03606    
03607    return res;
03608 }
03609 
03610 /*! \brief Output parking event to manager */
03611 static void post_manager_event(const char *s, struct parkeduser *pu)
03612 {
03613    manager_event(EVENT_FLAG_CALL, s,
03614       "Exten: %s\r\n"
03615       "Channel: %s\r\n"
03616       "Parkinglot: %s\r\n"
03617       "CallerIDNum: %s\r\n"
03618       "CallerIDName: %s\r\n"
03619       "UniqueID: %s\r\n\r\n",
03620       pu->parkingexten, 
03621       pu->chan->name,
03622       pu->parkinglot->name,
03623       S_COR(pu->chan->caller.id.number.valid, pu->chan->caller.id.number.str, "<unknown>"),
03624       S_COR(pu->chan->caller.id.name.valid, pu->chan->caller.id.name.str, "<unknown>"),
03625       pu->chan->uniqueid
03626       );
03627 }
03628 
03629 static char *callback_dialoptions(struct ast_flags *features_callee, struct ast_flags *features_caller, char *options, size_t len)
03630 {
03631    int i = 0;
03632    enum {
03633       OPT_CALLEE_REDIRECT   = 't',
03634       OPT_CALLER_REDIRECT   = 'T',
03635       OPT_CALLEE_AUTOMON    = 'w',
03636       OPT_CALLER_AUTOMON    = 'W',
03637       OPT_CALLEE_DISCONNECT = 'h',
03638       OPT_CALLER_DISCONNECT = 'H',
03639       OPT_CALLEE_PARKCALL   = 'k',
03640       OPT_CALLER_PARKCALL   = 'K',
03641    };
03642 
03643    memset(options, 0, len);
03644    if (ast_test_flag(features_caller, AST_FEATURE_REDIRECT) && i < len) {
03645       options[i++] = OPT_CALLER_REDIRECT;
03646    }
03647    if (ast_test_flag(features_caller, AST_FEATURE_AUTOMON) && i < len) {
03648       options[i++] = OPT_CALLER_AUTOMON;
03649    }
03650    if (ast_test_flag(features_caller, AST_FEATURE_DISCONNECT) && i < len) {
03651       options[i++] = OPT_CALLER_DISCONNECT;
03652    }
03653    if (ast_test_flag(features_caller, AST_FEATURE_PARKCALL) && i < len) {
03654       options[i++] = OPT_CALLER_PARKCALL;
03655    }
03656 
03657    if (ast_test_flag(features_callee, AST_FEATURE_REDIRECT) && i < len) {
03658       options[i++] = OPT_CALLEE_REDIRECT;
03659    }
03660    if (ast_test_flag(features_callee, AST_FEATURE_AUTOMON) && i < len) {
03661       options[i++] = OPT_CALLEE_AUTOMON;
03662    }
03663    if (ast_test_flag(features_callee, AST_FEATURE_DISCONNECT) && i < len) {
03664       options[i++] = OPT_CALLEE_DISCONNECT;
03665    }
03666    if (ast_test_flag(features_callee, AST_FEATURE_PARKCALL) && i < len) {
03667       options[i++] = OPT_CALLEE_PARKCALL;
03668    }
03669 
03670    return options;
03671 }
03672 
03673 /*! \brief Run management on parkinglots, called once per parkinglot */
03674 int manage_parkinglot(struct ast_parkinglot *curlot, const struct pollfd *pfds, const int nfds, struct pollfd **new_pfds, int *new_nfds, int *ms)
03675 {
03676    struct parkeduser *pu;
03677    int res = 0;
03678    char parkingslot[AST_MAX_EXTENSION];
03679 
03680    /* Lock parking list */
03681    AST_LIST_LOCK(&curlot->parkings);
03682    AST_LIST_TRAVERSE_SAFE_BEGIN(&curlot->parkings, pu, list) {
03683       struct ast_channel *chan = pu->chan;   /* shorthand */
03684       int tms;        /* timeout for this item */
03685       int x;          /* fd index in channel */
03686       struct ast_context *con;
03687 
03688       if (pu->notquiteyet) { /* Pretend this one isn't here yet */
03689          continue;
03690       }
03691       tms = ast_tvdiff_ms(ast_tvnow(), pu->start);
03692       if (tms > pu->parkingtime) {
03693          /* Stop music on hold */
03694          ast_indicate(pu->chan, AST_CONTROL_UNHOLD);
03695          /* Get chan, exten from derived kludge */
03696          if (pu->peername[0]) {
03697             char *peername = ast_strdupa(pu->peername);
03698             char *dash = strrchr(peername, '-');
03699             char *peername_flat; /* using something like DAHDI/52 for an extension name is NOT a good idea */
03700             int i;
03701 
03702             if (dash) {
03703                *dash = '\0';
03704             }
03705 
03706             peername_flat = ast_strdupa(peername);
03707             for (i = 0; peername_flat[i]; i++) {
03708                if (peername_flat[i] == '/') {
03709                   peername_flat[i]= '_';
03710                }
03711             }
03712 
03713             con = ast_context_find_or_create(NULL, NULL, pu->parkinglot->parking_con_dial, registrar);
03714             if (!con) {
03715                ast_log(LOG_ERROR, "Parking dial context '%s' does not exist and unable to create\n", pu->parkinglot->parking_con_dial);
03716             } else {
03717                char returnexten[AST_MAX_EXTENSION];
03718                struct ast_datastore *features_datastore;
03719                struct ast_dial_features *dialfeatures = NULL;
03720 
03721                ast_channel_lock(chan);
03722 
03723                if ((features_datastore = ast_channel_datastore_find(chan, &dial_features_info, NULL)))
03724                   dialfeatures = features_datastore->data;
03725 
03726                ast_channel_unlock(chan);
03727 
03728                if (!strncmp(peername, "Parked/", 7)) {
03729                   peername += 7;
03730                }
03731 
03732                if (dialfeatures) {
03733                   char buf[MAX_DIAL_FEATURE_OPTIONS] = {0,};
03734                   snprintf(returnexten, sizeof(returnexten), "%s,30,%s", peername, callback_dialoptions(&(dialfeatures->features_callee), &(dialfeatures->features_caller), buf, sizeof(buf)));
03735                } else { /* Existing default */
03736                   ast_log(LOG_NOTICE, "Dial features not found on %s, using default!\n", chan->name);
03737                   snprintf(returnexten, sizeof(returnexten), "%s,30,t", peername);
03738                }
03739 
03740                ast_add_extension2(con, 1, peername_flat, 1, NULL, NULL, "Dial", ast_strdup(returnexten), ast_free_ptr, registrar);
03741             }
03742             if (pu->options_specified == 1) {
03743                /* Park() was called with overriding return arguments, respect those arguments */
03744                set_c_e_p(chan, pu->context, pu->exten, pu->priority);
03745             } else {
03746                if (comebacktoorigin) {
03747                   set_c_e_p(chan, pu->parkinglot->parking_con_dial, peername_flat, 1);
03748                } else {
03749                   snprintf(parkingslot, sizeof(parkingslot), "%d", pu->parkingnum);
03750                   pbx_builtin_setvar_helper(chan, "PARKINGSLOT", parkingslot);
03751                   set_c_e_p(chan, "parkedcallstimeout", peername_flat, 1);
03752                }
03753             }
03754          } else {
03755             /* They've been waiting too long, send them back to where they came.  Theoretically they
03756                should have their original extensions and such, but we copy to be on the safe side */
03757             set_c_e_p(chan, pu->context, pu->exten, pu->priority);
03758          }
03759          post_manager_event("ParkedCallTimeOut", pu);
03760          ast_cel_report_event(pu->chan, AST_CEL_PARK_END, NULL, "ParkedCallTimeOut", NULL);
03761 
03762          ast_verb(2, "Timeout for %s parked on %d (%s). Returning to %s,%s,%d\n", pu->chan->name, pu->parkingnum, pu->parkinglot->name, pu->chan->context, pu->chan->exten, pu->chan->priority);
03763          /* Start up the PBX, or hang them up */
03764          if (ast_pbx_start(chan))  {
03765             ast_log(LOG_WARNING, "Unable to restart the PBX for user on '%s', hanging them up...\n", pu->chan->name);
03766             ast_hangup(chan);
03767          }
03768          /* And take them out of the parking lot */
03769          con = ast_context_find(pu->parkinglot->parking_con);
03770          if (con) {
03771             if (ast_context_remove_extension2(con, pu->parkingexten, 1, NULL, 0))
03772                ast_log(LOG_WARNING, "Whoa, failed to remove the parking extension!\n");
03773             else
03774                notify_metermaids(pu->parkingexten, curlot->parking_con, AST_DEVICE_NOT_INUSE);
03775          } else
03776             ast_log(LOG_WARNING, "Whoa, no parking context?\n");
03777          AST_LIST_REMOVE_CURRENT(list);
03778          free(pu);
03779       } else { /* still within parking time, process descriptors */
03780          for (x = 0; x < AST_MAX_FDS; x++) {
03781             struct ast_frame *f;
03782             int y;
03783 
03784             if (chan->fds[x] == -1) {
03785                continue;   /* nothing on this descriptor */
03786             }
03787 
03788             for (y = 0; y < nfds; y++) {
03789                if (pfds[y].fd == chan->fds[x]) {
03790                   /* Found poll record! */
03791                   break;
03792                }
03793             }
03794             if (y == nfds) {
03795                /* Not found */
03796                continue;
03797             }
03798 
03799             if (!(pfds[y].revents & (POLLIN | POLLERR))) {
03800                /* Next x */
03801                continue;
03802             }
03803 
03804             if (pfds[y].revents & POLLERR) {
03805                ast_set_flag(chan, AST_FLAG_EXCEPTION);
03806             } else {
03807                ast_clear_flag(chan, AST_FLAG_EXCEPTION);
03808             }
03809             chan->fdno = x;
03810 
03811             /* See if they need servicing */
03812             f = ast_read(pu->chan);
03813             /* Hangup? */
03814             if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass.integer ==  AST_CONTROL_HANGUP))) {
03815                if (f)
03816                   ast_frfree(f);
03817                post_manager_event("ParkedCallGiveUp", pu);
03818                ast_cel_report_event(pu->chan, AST_CEL_PARK_END, NULL, "ParkedCallGiveUp", NULL);
03819 
03820                /* There's a problem, hang them up*/
03821                ast_verb(2, "%s got tired of being parked\n", chan->name);
03822                ast_hangup(chan);
03823                /* And take them out of the parking lot */
03824                con = ast_context_find(curlot->parking_con);
03825                if (con) {
03826                   if (ast_context_remove_extension2(con, pu->parkingexten, 1, NULL, 0))
03827                      ast_log(LOG_WARNING, "Whoa, failed to remove the extension!\n");
03828                   else
03829                      notify_metermaids(pu->parkingexten, curlot->parking_con, AST_DEVICE_NOT_INUSE);
03830                } else
03831                   ast_log(LOG_WARNING, "Whoa, no parking context for parking lot %s?\n", curlot->name);
03832                AST_LIST_REMOVE_CURRENT(list);
03833                parkinglot_unref(pu->parkinglot);
03834                free(pu);
03835                break;
03836             } else {
03837                /* XXX Maybe we could do something with packets, like dial "0" for operator or something XXX */
03838                ast_frfree(f);
03839                if (pu->moh_trys < 3 && !chan->generatordata) {
03840                   ast_debug(1, "MOH on parked call stopped by outside source.  Restarting on channel %s.\n", chan->name);
03841                   ast_indicate_data(chan, AST_CONTROL_HOLD, 
03842                      S_OR(curlot->mohclass, NULL),
03843                      (!ast_strlen_zero(curlot->mohclass) ? strlen(curlot->mohclass) + 1 : 0));
03844                   pu->moh_trys++;
03845                }
03846                goto std;   /* XXX Ick: jumping into an else statement??? XXX */
03847             }
03848          } /* End for */
03849          if (x >= AST_MAX_FDS) {
03850 std:        for (x = 0; x < AST_MAX_FDS; x++) { /* mark fds for next round */
03851                if (chan->fds[x] > -1) {
03852                   void *tmp = ast_realloc(*new_pfds, (*new_nfds + 1) * sizeof(struct pollfd));
03853                   if (!tmp) {
03854                      continue;
03855                   }
03856                   *new_pfds = tmp;
03857                   (*new_pfds)[*new_nfds].fd = chan->fds[x];
03858                   (*new_pfds)[*new_nfds].events = POLLIN | POLLERR;
03859                   (*new_pfds)[*new_nfds].revents = 0;
03860                   (*new_nfds)++;
03861                }
03862             }
03863             /* Keep track of our shortest wait */
03864             if (tms < *ms || *ms < 0) {
03865                *ms = tms;
03866             }
03867          }
03868       }
03869    }
03870    AST_LIST_TRAVERSE_SAFE_END;
03871    AST_LIST_UNLOCK(&curlot->parkings);
03872 
03873    return res;
03874 }
03875 
03876 /*! 
03877  * \brief Take care of parked calls and unpark them if needed 
03878  * \param ignore unused var.
03879  * 
03880  * Start inf loop, lock parking lot, check if any parked channels have gone above timeout
03881  * if so, remove channel from parking lot and return it to the extension that parked it.
03882  * Check if parked channel decided to hangup, wait until next FD via select().
03883 */
03884 static void *do_parking_thread(void *ignore)
03885 {
03886    struct pollfd *pfds = NULL, *new_pfds = NULL;
03887    int nfds = 0, new_nfds = 0;
03888 
03889    for (;;) {
03890       struct ao2_iterator iter;
03891       struct ast_parkinglot *curlot;
03892       int ms = -1;   /* poll2 timeout, uninitialized */
03893       iter = ao2_iterator_init(parkinglots, 0);
03894 
03895       while ((curlot = ao2_iterator_next(&iter))) {
03896          manage_parkinglot(curlot, pfds, nfds, &new_pfds, &new_nfds, &ms);
03897          ao2_ref(curlot, -1);
03898       }
03899       ao2_iterator_destroy(&iter);
03900 
03901       /* Recycle */
03902       ast_free(pfds);
03903       pfds = new_pfds;
03904       nfds = new_nfds;
03905       new_pfds = NULL;
03906       new_nfds = 0;
03907 
03908       /* Wait for something to happen */
03909       ast_poll(pfds, nfds, ms);
03910       pthread_testcancel();
03911    }
03912    /* If this WERE reached, we'd need to free(pfds) */
03913    return NULL;   /* Never reached */
03914 }
03915 
03916 /*! \brief Find parkinglot by name */
03917 struct ast_parkinglot *find_parkinglot(const char *name)
03918 {
03919    struct ast_parkinglot *parkinglot;
03920 
03921    if (ast_strlen_zero(name)) {
03922       return NULL;
03923    }
03924 
03925    parkinglot = ao2_find(parkinglots, (void *) name, 0);
03926    if (parkinglot) {
03927       ast_debug(1, "Found Parkinglot: %s\n", parkinglot->name);
03928    }
03929 
03930    return parkinglot;
03931 }
03932 
03933 /*! \brief Copy parkinglot and store it with new name */
03934 struct ast_parkinglot *copy_parkinglot(const char *name, const struct ast_parkinglot *parkinglot) {
03935    struct ast_parkinglot *copylot;
03936 
03937    if (ast_strlen_zero(name)) { /* No name specified */
03938       return NULL;
03939    }
03940    if ((copylot = find_parkinglot(name))) { /* Parkinglot with that name already exists */
03941       if (copylot) {
03942          ao2_ref(copylot, -1);
03943       }
03944       return NULL;
03945    }
03946 
03947    copylot = create_parkinglot(name);
03948    ast_debug(1, "Building parking lot %s\n", name);
03949 
03950    memcpy(copylot, parkinglot, sizeof(struct ast_parkinglot));
03951    ast_copy_string(copylot->name, name, sizeof(copylot->name));
03952    AST_LIST_HEAD_INIT(&copylot->parkings);
03953 
03954    return copylot;
03955 }
03956 
03957 AST_APP_OPTIONS(park_call_options, BEGIN_OPTIONS
03958    AST_APP_OPTION('r', AST_PARK_OPT_RINGING),
03959    AST_APP_OPTION('R', AST_PARK_OPT_RANDOMIZE),
03960    AST_APP_OPTION('s', AST_PARK_OPT_SILENCE),
03961 END_OPTIONS );
03962 
03963 /*! \brief Park a call */
03964 static int park_call_exec(struct ast_channel *chan, const char *data)
03965 {
03966    /* Cache the original channel name in case we get masqueraded in the middle
03967     * of a park--it is still theoretically possible for a transfer to happen before
03968     * we get here, but it is _really_ unlikely */
03969    char *orig_chan_name = ast_strdupa(chan->name);
03970    char orig_exten[AST_MAX_EXTENSION];
03971    int orig_priority = chan->priority;
03972 
03973    /* Data is unused at the moment but could contain a parking
03974       lot context eventually */
03975    int res = 0;
03976 
03977    char *parse = NULL;
03978    AST_DECLARE_APP_ARGS(app_args,
03979       AST_APP_ARG(timeout);
03980       AST_APP_ARG(return_con);
03981       AST_APP_ARG(return_ext);
03982       AST_APP_ARG(return_pri);
03983       AST_APP_ARG(options);
03984    );
03985 
03986    parse = ast_strdupa(data);
03987    AST_STANDARD_APP_ARGS(app_args, parse);
03988 
03989    ast_copy_string(orig_exten, chan->exten, sizeof(orig_exten));
03990 
03991    /* Setup the exten/priority to be s/1 since we don't know
03992       where this call should return */
03993    strcpy(chan->exten, "s");
03994    chan->priority = 1;
03995 
03996    /* Answer if call is not up */
03997    if (chan->_state != AST_STATE_UP)
03998       res = ast_answer(chan);
03999 
04000    /* Sleep to allow VoIP streams to settle down */
04001    if (!res)
04002       res = ast_safe_sleep(chan, 1000);
04003 
04004    /* Park the call */
04005    if (!res) {
04006       struct ast_park_call_args args = {
04007          .orig_chan_name = orig_chan_name,
04008       };
04009       struct ast_flags flags = { 0 };
04010 
04011       if (parse) {
04012          if (!ast_strlen_zero(app_args.timeout)) {
04013             if (sscanf(app_args.timeout, "%30d", &args.timeout) != 1) {
04014                ast_log(LOG_WARNING, "Invalid timeout '%s' provided\n", app_args.timeout);
04015                args.timeout = 0;
04016             }
04017          }
04018          if (!ast_strlen_zero(app_args.return_con)) {
04019             args.return_con = app_args.return_con;
04020          }
04021          if (!ast_strlen_zero(app_args.return_ext)) {
04022             args.return_ext = app_args.return_ext;
04023          }
04024          if (!ast_strlen_zero(app_args.return_pri)) {
04025             if (sscanf(app_args.return_pri, "%30d", &args.return_pri) != 1) {
04026                ast_log(LOG_WARNING, "Invalid priority '%s' specified\n", app_args.return_pri);
04027                args.return_pri = 0;
04028             }
04029          }
04030       }
04031 
04032       ast_app_parse_options(park_call_options, &flags, NULL, app_args.options);
04033       args.flags = flags.flags;
04034 
04035       args.parkinglot = ao2_callback(parkinglots, 0, find_parkinglot_by_exten_cb, &orig_exten);
04036       res = masq_park_call_announce(chan, chan, &args);
04037       /* Continue on in the dialplan */
04038       if (res == 1) {
04039          ast_copy_string(chan->exten, orig_exten, sizeof(chan->exten));
04040          chan->priority = orig_priority;
04041          res = 0;
04042       } else if (!res) {
04043          res = 1;
04044       }
04045    }
04046 
04047    return res;
04048 }
04049 
04050 /*! \brief Pickup parked call */
04051 static int park_exec_full(struct ast_channel *chan, const char *data)
04052 {
04053    int res = 0;
04054    struct ast_channel *peer=NULL;
04055    struct parkeduser *pu;
04056    struct ast_context *con;
04057    int park = 0;
04058    struct ast_bridge_config config;
04059    struct ast_parkinglot *parkinglot;
04060 
04061    if (data) {
04062       park = atoi((char *) data);
04063    }
04064 
04065    parkinglot = ao2_callback(parkinglots, 0, find_parkinglot_by_position_cb, (void *) &park);
04066    if (!parkinglot)
04067       parkinglot = default_parkinglot;
04068 
04069    AST_LIST_LOCK(&parkinglot->parkings);
04070    AST_LIST_TRAVERSE_SAFE_BEGIN(&parkinglot->parkings, pu, list) {
04071       if (!pu->notquiteyet && (!data || pu->parkingnum == park)) {
04072          if (pu->chan->pbx) { /* do not allow call to be picked up until the PBX thread is finished */
04073             AST_LIST_UNLOCK(&parkinglot->parkings);
04074             return -1;
04075          }
04076          AST_LIST_REMOVE_CURRENT(list);
04077          break;
04078       }
04079    }
04080    AST_LIST_TRAVERSE_SAFE_END;
04081    AST_LIST_UNLOCK(&parkinglot->parkings);
04082 
04083    if (pu) {
04084       peer = pu->chan;
04085       con = ast_context_find(parkinglot->parking_con);
04086       if (con) {
04087          if (ast_context_remove_extension2(con, pu->parkingexten, 1, NULL, 0))
04088             ast_log(LOG_WARNING, "Whoa, failed to remove the extension!\n");
04089          else
04090             notify_metermaids(pu->parkingexten, parkinglot->parking_con, AST_DEVICE_NOT_INUSE);
04091       } else
04092          ast_log(LOG_WARNING, "Whoa, no parking context?\n");
04093 
04094       ast_cel_report_event(pu->chan, AST_CEL_PARK_END, NULL, "UnParkedCall", chan);
04095       ast_manager_event(pu->chan, EVENT_FLAG_CALL, "UnParkedCall",
04096          "Exten: %s\r\n"
04097          "Channel: %s\r\n"
04098          "From: %s\r\n"
04099          "CallerIDNum: %s\r\n"
04100          "CallerIDName: %s\r\n",
04101          pu->parkingexten, pu->chan->name, chan->name,
04102          S_COR(pu->chan->caller.id.number.valid, pu->chan->caller.id.number.str, "<unknown>"),
04103          S_COR(pu->chan->caller.id.name.valid, pu->chan->caller.id.name.str, "<unknown>")
04104          );
04105 
04106       ast_free(pu);
04107    }
04108    /* JK02: it helps to answer the channel if not already up */
04109    if (chan->_state != AST_STATE_UP)
04110       ast_answer(chan);
04111 
04112    //XXX Why do we unlock here ?
04113    // uncomment it for now, till my setup with debug_threads and detect_deadlocks starts to complain
04114    //ASTOBJ_UNLOCK(parkinglot);
04115 
04116    if (peer) {
04117       struct ast_datastore *features_datastore;
04118       struct ast_dial_features *dialfeatures = NULL;
04119 
04120       /* Play a courtesy to the source(s) configured to prefix the bridge connecting */
04121 
04122       if (!ast_strlen_zero(courtesytone)) {
04123          int error = 0;
04124          ast_indicate(peer, AST_CONTROL_UNHOLD);
04125          if (parkedplay == 0) {
04126             error = ast_stream_and_wait(chan, courtesytone, "");
04127          } else if (parkedplay == 1) {
04128             error = ast_stream_and_wait(peer, courtesytone, "");
04129          } else if (parkedplay == 2) {
04130             if (!ast_streamfile(chan, courtesytone, chan->language) &&
04131                   !ast_streamfile(peer, courtesytone, chan->language)) {
04132                /*! \todo XXX we would like to wait on both! */
04133                res = ast_waitstream(chan, "");
04134                if (res >= 0)
04135                   res = ast_waitstream(peer, "");
04136                if (res < 0)
04137                   error = 1;
04138             }
04139          }
04140          if (error) {
04141             ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
04142             ast_hangup(peer);
04143             return -1;
04144          }
04145       } else
04146          ast_indicate(peer, AST_CONTROL_UNHOLD);
04147 
04148       res = ast_channel_make_compatible(chan, peer);
04149       if (res < 0) {
04150          ast_log(LOG_WARNING, "Could not make channels %s and %s compatible for bridge\n", chan->name, peer->name);
04151          ast_hangup(peer);
04152          return -1;
04153       }
04154       /* This runs sorta backwards, since we give the incoming channel control, as if it
04155          were the person called. */
04156       ast_verb(3, "Channel %s connected to parked call %d\n", chan->name, park);
04157 
04158       pbx_builtin_setvar_helper(chan, "PARKEDCHANNEL", peer->name);
04159       ast_cdr_setdestchan(chan->cdr, peer->name);
04160       memset(&config, 0, sizeof(struct ast_bridge_config));
04161 
04162       /* Get datastore for peer and apply it's features to the callee side of the bridge config */
04163       ast_channel_lock(peer);
04164       if ((features_datastore = ast_channel_datastore_find(peer, &dial_features_info, NULL))) {
04165          dialfeatures = features_datastore->data;
04166       }
04167       ast_channel_unlock(peer);
04168 
04169       /* When the datastores for both caller and callee are created, both the callee and caller channels
04170        * use the features_caller flag variable to represent themselves. With that said, the config.features_callee
04171        * flags should be copied from the datastore's caller feature flags regardless if peer was a callee
04172        * or caller. */
04173       if (dialfeatures) {
04174          ast_copy_flags(&(config.features_callee), &(dialfeatures->features_caller), AST_FLAGS_ALL);
04175       }
04176 
04177       if ((parkinglot->parkedcalltransfers == AST_FEATURE_FLAG_BYCALLEE) || (parkinglot->parkedcalltransfers == AST_FEATURE_FLAG_BYBOTH)) {
04178          ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
04179       }
04180       if ((parkinglot->parkedcalltransfers == AST_FEATURE_FLAG_BYCALLER) || (parkinglot->parkedcalltransfers == AST_FEATURE_FLAG_BYBOTH)) {
04181          ast_set_flag(&(config.features_caller), AST_FEATURE_REDIRECT);
04182       }
04183       if ((parkinglot->parkedcallreparking == AST_FEATURE_FLAG_BYCALLEE) || (parkinglot->parkedcallreparking == AST_FEATURE_FLAG_BYBOTH)) {
04184          ast_set_flag(&(config.features_callee), AST_FEATURE_PARKCALL);
04185       }
04186       if ((parkinglot->parkedcallreparking == AST_FEATURE_FLAG_BYCALLER) || (parkinglot->parkedcallreparking == AST_FEATURE_FLAG_BYBOTH)) {
04187          ast_set_flag(&(config.features_caller), AST_FEATURE_PARKCALL);
04188       }
04189       if ((parkinglot->parkedcallhangup == AST_FEATURE_FLAG_BYCALLEE) || (parkinglot->parkedcallhangup == AST_FEATURE_FLAG_BYBOTH)) {
04190          ast_set_flag(&(config.features_callee), AST_FEATURE_DISCONNECT);
04191       }
04192       if ((parkinglot->parkedcallhangup == AST_FEATURE_FLAG_BYCALLER) || (parkinglot->parkedcallhangup == AST_FEATURE_FLAG_BYBOTH)) {
04193          ast_set_flag(&(config.features_caller), AST_FEATURE_DISCONNECT);
04194       }
04195       if ((parkinglot->parkedcallrecording == AST_FEATURE_FLAG_BYCALLEE) || (parkinglot->parkedcallrecording == AST_FEATURE_FLAG_BYBOTH)) {
04196          ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMON);
04197       }
04198       if ((parkinglot->parkedcallrecording == AST_FEATURE_FLAG_BYCALLER) || (parkinglot->parkedcallrecording == AST_FEATURE_FLAG_BYBOTH)) {
04199          ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMON);
04200       }
04201 
04202       parkinglot_unref(parkinglot);
04203       res = ast_bridge_call(chan, peer, &config);
04204 
04205       pbx_builtin_setvar_helper(chan, "PARKEDCHANNEL", peer->name);
04206       ast_cdr_setdestchan(chan->cdr, peer->name);
04207 
04208       /* Simulate the PBX hanging up */
04209       ast_hangup(peer);
04210       return -1;
04211    } else {
04212       /*! \todo XXX Play a message XXX */
04213       if (ast_stream_and_wait(chan, "pbx-invalidpark", ""))
04214          ast_log(LOG_WARNING, "ast_streamfile of %s failed on %s\n", "pbx-invalidpark", chan->name);
04215       ast_verb(3, "Channel %s tried to talk to nonexistent parked call %d\n", chan->name, park);
04216       res = -1;
04217    }
04218 
04219    return -1;
04220 }
04221 
04222 static int park_exec(struct ast_channel *chan, const char *data) 
04223 {
04224    return park_exec_full(chan, data);
04225 }
04226 
04227 /*! \brief Unreference parkinglot object. If no more references,
04228    then go ahead and delete it */
04229 static void parkinglot_unref(struct ast_parkinglot *parkinglot) 
04230 {
04231    int refcount = ao2_ref(parkinglot, -1);
04232    ast_debug(3, "Multiparking: %s refcount now %d\n", parkinglot->name, refcount - 1);
04233 }
04234 
04235 static struct ast_parkinglot *parkinglot_addref(struct ast_parkinglot *parkinglot)
04236 {
04237    int refcount = ao2_ref(parkinglot, +1);
04238    ast_debug(3, "Multiparking: %s refcount now %d\n", parkinglot->name, refcount + 1);
04239    return parkinglot;
04240 }
04241 
04242 /*! \brief Allocate parking lot structure */
04243 static struct ast_parkinglot *create_parkinglot(const char *name)
04244 {
04245    struct ast_parkinglot *newlot = (struct ast_parkinglot *) NULL;
04246 
04247    if (!name)
04248       return NULL;
04249 
04250    newlot = ao2_alloc(sizeof(*newlot), parkinglot_destroy);
04251    if (!newlot)
04252       return NULL;
04253    
04254    ast_copy_string(newlot->name, name, sizeof(newlot->name));
04255    AST_LIST_HEAD_INIT(&newlot->parkings);
04256 
04257    return newlot;
04258 }
04259 
04260 /*! \brief Destroy a parking lot */
04261 static void parkinglot_destroy(void *obj)
04262 {
04263    struct ast_parkinglot *ruin = obj;
04264    struct ast_context *con;
04265    con = ast_context_find(ruin->parking_con);
04266    if (con)
04267       ast_context_destroy(con, registrar);
04268 }
04269 
04270 /*! 
04271  * \brief Add parking hints for all defined parking lots 
04272  * \param context
04273  * \param start starting parkinglot number
04274  * \param stop ending parkinglot number
04275 */
04276 static void park_add_hints(char *context, int start, int stop)
04277 {
04278    int numext;
04279    char device[AST_MAX_EXTENSION];
04280    char exten[10];
04281 
04282    for (numext = start; numext <= stop; numext++) {
04283       snprintf(exten, sizeof(exten), "%d", numext);
04284       snprintf(device, sizeof(device), "park:%s@%s", exten, context);
04285       ast_add_extension(context, 1, exten, PRIORITY_HINT, NULL, NULL, device, NULL, NULL, registrar);
04286    }
04287 }
04288 
04289 /*! \brief Build parkinglot from configuration and chain it in if it doesn't already exist */
04290 static struct ast_parkinglot *build_parkinglot(char *name, struct ast_variable *var)
04291 {
04292    struct ast_parkinglot *parkinglot;
04293    struct ast_context *con = NULL;
04294 
04295    struct ast_variable *confvar = var;
04296    int error = 0;
04297    int start = 0, end = 0;
04298    int oldparkinglot = 0;
04299 
04300    parkinglot = find_parkinglot(name);
04301    if (parkinglot)
04302       oldparkinglot = 1;
04303    else
04304       parkinglot = create_parkinglot(name);
04305 
04306    if (!parkinglot)
04307       return NULL;
04308 
04309    ao2_lock(parkinglot);
04310 
04311    ast_debug(1, "Building parking lot %s\n", name);
04312 
04313    /* Do some config stuff */
04314    while(confvar) {
04315       if (!strcasecmp(confvar->name, "context")) {
04316          ast_copy_string(parkinglot->parking_con, confvar->value, sizeof(parkinglot->parking_con));
04317       } else if (!strcasecmp(confvar->name, "parkext")) {
04318          ast_copy_string(parkinglot->parkext, confvar->value, sizeof(parkinglot->parkext));
04319       } else if (!strcasecmp(confvar->name, "parkingtime")) {
04320          if ((sscanf(confvar->value, "%30d", &parkinglot->parkingtime) != 1) || (parkinglot->parkingtime < 1)) {
04321             ast_log(LOG_WARNING, "%s is not a valid parkingtime\n", confvar->value);
04322             parkinglot->parkingtime = DEFAULT_PARK_TIME;
04323          } else
04324             parkinglot->parkingtime = parkinglot->parkingtime * 1000;
04325       } else if (!strcasecmp(confvar->name, "parkpos")) {
04326          if (sscanf(confvar->value, "%30d-%30d", &start, &end) != 2) {
04327             ast_log(LOG_WARNING, "Format for parking positions is a-b, where a and b are numbers at line %d of parking.conf\n", confvar->lineno);
04328             error = 1;
04329          } else {
04330             parkinglot->parking_start = start;
04331             parkinglot->parking_stop = end;
04332          }
04333       } else if (!strcasecmp(confvar->name, "findslot")) {
04334          parkinglot->parkfindnext = (!strcasecmp(confvar->value, "next"));
04335       } else if (!strcasecmp(confvar->name, "parkedcalltransfers")) {
04336                         ast_log(LOG_DEBUG, "Setting parking lot %s %s to %s\n", name, confvar->name, confvar->value);
04337                         if (!strcasecmp(confvar->value, "both"))
04338                                 parkinglot->parkedcalltransfers = AST_FEATURE_FLAG_BYBOTH;
04339                         else if (!strcasecmp(confvar->value, "caller"))
04340                                 parkinglot->parkedcalltransfers = AST_FEATURE_FLAG_BYCALLER;
04341                         else if (!strcasecmp(confvar->value, "callee"))
04342                                 parkinglot->parkedcalltransfers = AST_FEATURE_FLAG_BYCALLEE;
04343                 } else if (!strcasecmp(confvar->name, "parkedcallreparking")) {
04344                         ast_log(LOG_DEBUG, "Setting parking lot %s %s to %s\n", name, confvar->name, confvar->value);
04345                         if (!strcasecmp(confvar->value, "both"))
04346                                 parkinglot->parkedcallreparking = AST_FEATURE_FLAG_BYBOTH;
04347                         else if (!strcasecmp(confvar->value, "caller"))
04348                                 parkinglot->parkedcallreparking = AST_FEATURE_FLAG_BYCALLER;
04349                         else if (!strcasecmp(confvar->value, "callee"))
04350                                 parkinglot->parkedcallreparking = AST_FEATURE_FLAG_BYCALLEE;
04351                 } else if (!strcasecmp(confvar->name, "parkedcallhangup")) {
04352                         ast_log(LOG_DEBUG, "Setting parking lot %s %s to %s\n", name, confvar->name, confvar->value);
04353                         if (!strcasecmp(confvar->value, "both"))
04354                                 parkinglot->parkedcallhangup = AST_FEATURE_FLAG_BYBOTH;
04355                         else if (!strcasecmp(confvar->value, "caller"))
04356                                 parkinglot->parkedcallhangup = AST_FEATURE_FLAG_BYCALLER;
04357                         else if (!strcasecmp(confvar->value, "callee"))
04358                                 parkinglot->parkedcallhangup = AST_FEATURE_FLAG_BYCALLEE;
04359                 } else if (!strcasecmp(confvar->name, "parkedcallrecording")) {
04360                         ast_log(LOG_DEBUG, "Setting parking lot %s %s to %s\n", name, confvar->name, confvar->value);
04361                         if (!strcasecmp(confvar->value, "both"))
04362                                 parkinglot->parkedcallrecording = AST_FEATURE_FLAG_BYBOTH;
04363                         else if (!strcasecmp(confvar->value, "caller"))
04364                                 parkinglot->parkedcallrecording = AST_FEATURE_FLAG_BYCALLER;
04365                         else if (!strcasecmp(confvar->value, "callee"))
04366                                 parkinglot->parkedcallrecording = AST_FEATURE_FLAG_BYCALLEE;
04367                 }
04368       confvar = confvar->next;
04369    }
04370    /* make sure parkingtime is set if not specified */
04371    if (parkinglot->parkingtime == 0) {
04372       parkinglot->parkingtime = DEFAULT_PARK_TIME;
04373    }
04374    if (ast_strlen_zero(parkinglot->parkext)) {
04375       ast_debug(2, "no parkext specified for %s - setting it to %s\n", parkinglot->name, DEFAULT_PARK_EXTENSION);
04376       ast_copy_string(parkinglot->parkext, DEFAULT_PARK_EXTENSION, sizeof(parkinglot->parkext));
04377    }
04378 
04379    if (!var) { /* Default parking lot */
04380       ast_copy_string(parkinglot->parking_con, "parkedcalls", sizeof(parkinglot->parking_con));
04381       ast_copy_string(parkinglot->parking_con_dial, "park-dial", sizeof(parkinglot->parking_con_dial));
04382       ast_copy_string(parkinglot->mohclass, "default", sizeof(parkinglot->mohclass));
04383    }
04384 
04385    /* Check for errors */
04386    if (ast_strlen_zero(parkinglot->parking_con)) {
04387       ast_log(LOG_WARNING, "Parking lot %s lacks context\n", name);
04388       error = 1;
04389    }
04390 
04391    /* Create context */
04392    if (!error && !(con = ast_context_find_or_create(NULL, NULL, parkinglot->parking_con, registrar))) {
04393       ast_log(LOG_ERROR, "Parking context '%s' does not exist and unable to create\n", parkinglot->parking_con);
04394       error = 1;
04395    }
04396 
04397    /* Add a parking extension into the context */
04398    if (!error && !oldparkinglot) {
04399       if (!ast_strlen_zero(parkinglot->parkext)) {
04400          if (ast_add_extension2(con, 1, parkinglot->parkext, 1, NULL, NULL, parkcall, strdup(""), ast_free_ptr, registrar) == -1)
04401             error = 1;
04402       }
04403    }
04404 
04405    /* Add parking hints */
04406    if (parkinglot->parkaddhints)
04407       park_add_hints(parkinglot->parking_con, parkinglot->parking_start, parkinglot->parking_stop);
04408 
04409    ao2_unlock(parkinglot);
04410 
04411    if (error) {
04412       ast_log(LOG_WARNING, "Parking %s not open for business. Configuration error.\n", name);
04413       parkinglot_destroy(parkinglot);
04414       parkinglot_unref(parkinglot);
04415       return NULL;
04416    }
04417    ast_debug(1, "Parking %s now open for business. (start exten %d end %d)\n", name, start, end);
04418    parkinglot->the_mark = 0;
04419 
04420    /* Move it into the list, if it wasn't already there */
04421    if (!oldparkinglot) {
04422       ao2_link(parkinglots, parkinglot);
04423    }
04424    parkinglot_unref(parkinglot);
04425 
04426    return parkinglot;
04427 }
04428 
04429 static int load_config(void) 
04430 {
04431    int start = 0, end = 0;
04432    int res;
04433    int i;
04434    struct ast_context *con = NULL;
04435    struct ast_config *cfg = NULL;
04436    struct ast_variable *var = NULL;
04437    struct feature_group *fg = NULL;
04438    struct ast_flags config_flags = { 0 };
04439    char *ctg; 
04440    static const char * const categories[] = { 
04441       /* Categories in features.conf that are not
04442        * to be parsed as group categories
04443        */
04444       "general",
04445       "featuremap",
04446       "applicationmap"
04447    };
04448 
04449    default_parkinglot = build_parkinglot(DEFAULT_PARKINGLOT, NULL);
04450    if (default_parkinglot) {
04451       ao2_lock(default_parkinglot);
04452       ast_copy_string(default_parkinglot->parkext, DEFAULT_PARK_EXTENSION, sizeof(default_parkinglot->parkext));
04453       default_parkinglot->parking_start = 701;
04454       default_parkinglot->parking_stop = 750;
04455       default_parkinglot->parking_offset = 0;
04456       default_parkinglot->parkfindnext = 0;
04457       default_parkinglot->parkingtime = DEFAULT_PARK_TIME;
04458       ao2_unlock(default_parkinglot);
04459    }
04460    
04461    if (default_parkinglot) {
04462       ast_debug(1, "Configuration of default parkinglot done.\n");
04463    } else {
04464       ast_log(LOG_ERROR, "Configuration of default parkinglot failed.\n");
04465       return -1;
04466    }
04467 
04468    /* Reset to defaults */
04469    strcpy(default_parkinglot->parkext, DEFAULT_PARK_EXTENSION);
04470    strcpy(pickup_ext, "*8");
04471    courtesytone[0] = '\0';
04472    strcpy(xfersound, "beep");
04473    strcpy(xferfailsound, "pbx-invalid");
04474    pickupsound[0] = '\0';
04475    pickupfailsound[0] = '\0';
04476    adsipark = 0;
04477    comebacktoorigin = 1;
04478    parkeddynamic = 0;
04479 
04480    default_parkinglot->parkaddhints = 0;
04481    default_parkinglot->parkedcalltransfers = 0;
04482    default_parkinglot->parkedcallreparking = 0;
04483    default_parkinglot->parkedcallrecording = 0;
04484    default_parkinglot->parkedcallhangup = 0;
04485 
04486    transferdigittimeout = DEFAULT_TRANSFER_DIGIT_TIMEOUT;
04487    featuredigittimeout = DEFAULT_FEATURE_DIGIT_TIMEOUT;
04488    atxfernoanswertimeout = DEFAULT_NOANSWER_TIMEOUT_ATTENDED_TRANSFER;
04489    atxferloopdelay = DEFAULT_ATXFER_LOOP_DELAY;
04490    atxferdropcall = DEFAULT_ATXFER_DROP_CALL;
04491    atxfercallbackretries = DEFAULT_ATXFER_CALLBACK_RETRIES;
04492 
04493    cfg = ast_config_load2("features.conf", "features", config_flags);
04494    if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
04495       ast_log(LOG_WARNING,"Could not load features.conf\n");
04496       return 0;
04497    }
04498    for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
04499       if (!strcasecmp(var->name, "parkext")) {
04500          ast_copy_string(default_parkinglot->parkext, var->value, sizeof(default_parkinglot->parkext));
04501       } else if (!strcasecmp(var->name, "context")) {
04502          ast_copy_string(default_parkinglot->parking_con, var->value, sizeof(default_parkinglot->parking_con));
04503       } else if (!strcasecmp(var->name, "parkingtime")) {
04504          if ((sscanf(var->value, "%30d", &default_parkinglot->parkingtime) != 1) || (default_parkinglot->parkingtime < 1)) {
04505             ast_log(LOG_WARNING, "%s is not a valid parkingtime\n", var->value);
04506             default_parkinglot->parkingtime = DEFAULT_PARK_TIME;
04507          } else
04508             default_parkinglot->parkingtime = default_parkinglot->parkingtime * 1000;
04509       } else if (!strcasecmp(var->name, "parkpos")) {
04510          if (sscanf(var->value, "%30d-%30d", &start, &end) != 2) {
04511             ast_log(LOG_WARNING, "Format for parking positions is a-b, where a and b are numbers at line %d of features.conf\n", var->lineno);
04512          } else if (default_parkinglot) {
04513             default_parkinglot->parking_start = start;
04514             default_parkinglot->parking_stop = end;
04515          } else {
04516             ast_log(LOG_WARNING, "No default parking lot!\n");
04517          }
04518       } else if (!strcasecmp(var->name, "findslot")) {
04519          default_parkinglot->parkfindnext = (!strcasecmp(var->value, "next"));
04520       } else if (!strcasecmp(var->name, "parkinghints")) {
04521          default_parkinglot->parkaddhints = ast_true(var->value);
04522       } else if (!strcasecmp(var->name, "parkedcalltransfers")) {
04523          if (!strcasecmp(var->value, "both"))
04524             default_parkinglot->parkedcalltransfers = AST_FEATURE_FLAG_BYBOTH;
04525          else if (!strcasecmp(var->value, "caller"))
04526             default_parkinglot->parkedcalltransfers = AST_FEATURE_FLAG_BYCALLER;
04527          else if (!strcasecmp(var->value, "callee"))
04528             default_parkinglot->parkedcalltransfers = AST_FEATURE_FLAG_BYCALLEE;
04529       } else if (!strcasecmp(var->name, "parkedcallreparking")) {
04530          if (!strcasecmp(var->value, "both"))
04531             default_parkinglot->parkedcallreparking = AST_FEATURE_FLAG_BYBOTH;
04532          else if (!strcasecmp(var->value, "caller"))
04533             default_parkinglot->parkedcallreparking = AST_FEATURE_FLAG_BYCALLER;
04534          else if (!strcasecmp(var->value, "callee"))
04535             default_parkinglot->parkedcallreparking = AST_FEATURE_FLAG_BYCALLEE;
04536       } else if (!strcasecmp(var->name, "parkedcallhangup")) {
04537          if (!strcasecmp(var->value, "both"))
04538             default_parkinglot->parkedcallhangup = AST_FEATURE_FLAG_BYBOTH;
04539          else if (!strcasecmp(var->value, "caller"))
04540             default_parkinglot->parkedcallhangup = AST_FEATURE_FLAG_BYCALLER;
04541          else if (!strcasecmp(var->value, "callee"))
04542             default_parkinglot->parkedcallhangup = AST_FEATURE_FLAG_BYCALLEE;
04543       } else if (!strcasecmp(var->name, "parkedcallrecording")) {
04544          if (!strcasecmp(var->value, "both"))
04545             default_parkinglot->parkedcallrecording = AST_FEATURE_FLAG_BYBOTH;
04546          else if (!strcasecmp(var->value, "caller"))
04547             default_parkinglot->parkedcallrecording = AST_FEATURE_FLAG_BYCALLER;
04548          else if (!strcasecmp(var->value, "callee"))
04549             default_parkinglot->parkedcallrecording = AST_FEATURE_FLAG_BYCALLEE;
04550       } else if (!strcasecmp(var->name, "parkeddynamic")) {
04551          parkeddynamic = ast_true(var->value);
04552       } else if (!strcasecmp(var->name, "adsipark")) {
04553          adsipark = ast_true(var->value);
04554       } else if (!strcasecmp(var->name, "transferdigittimeout")) {
04555          if ((sscanf(var->value, "%30d", &transferdigittimeout) != 1) || (transferdigittimeout < 1)) {
04556             ast_log(LOG_WARNING, "%s is not a valid transferdigittimeout\n", var->value);
04557             transferdigittimeout = DEFAULT_TRANSFER_DIGIT_TIMEOUT;
04558          } else
04559             transferdigittimeout = transferdigittimeout * 1000;
04560       } else if (!strcasecmp(var->name, "featuredigittimeout")) {
04561          if ((sscanf(var->value, "%30d", &featuredigittimeout) != 1) || (featuredigittimeout < 1)) {
04562             ast_log(LOG_WARNING, "%s is not a valid featuredigittimeout\n", var->value);
04563             featuredigittimeout = DEFAULT_FEATURE_DIGIT_TIMEOUT;
04564          }
04565       } else if (!strcasecmp(var->name, "atxfernoanswertimeout")) {
04566          if ((sscanf(var->value, "%30d", &atxfernoanswertimeout) != 1) || (atxfernoanswertimeout < 1)) {
04567             ast_log(LOG_WARNING, "%s is not a valid atxfernoanswertimeout\n", var->value);
04568             atxfernoanswertimeout = DEFAULT_NOANSWER_TIMEOUT_ATTENDED_TRANSFER;
04569          } else
04570             atxfernoanswertimeout = atxfernoanswertimeout * 1000;
04571       } else if (!strcasecmp(var->name, "atxferloopdelay")) {
04572          if ((sscanf(var->value, "%30u", &atxferloopdelay) != 1)) {
04573             ast_log(LOG_WARNING, "%s is not a valid atxferloopdelay\n", var->value);
04574             atxferloopdelay = DEFAULT_ATXFER_LOOP_DELAY;
04575          } else 
04576             atxferloopdelay *= 1000;
04577       } else if (!strcasecmp(var->name, "atxferdropcall")) {
04578          atxferdropcall = ast_true(var->value);
04579       } else if (!strcasecmp(var->name, "atxfercallbackretries")) {
04580          if ((sscanf(var->value, "%30u", &atxferloopdelay) != 1)) {
04581             ast_log(LOG_WARNING, "%s is not a valid atxfercallbackretries\n", var->value);
04582             atxfercallbackretries = DEFAULT_ATXFER_CALLBACK_RETRIES;
04583          }
04584       } else if (!strcasecmp(var->name, "courtesytone")) {
04585          ast_copy_string(courtesytone, var->value, sizeof(courtesytone));
04586       }  else if (!strcasecmp(var->name, "parkedplay")) {
04587          if (!strcasecmp(var->value, "both"))
04588             parkedplay = 2;
04589          else if (!strcasecmp(var->value, "parked"))
04590             parkedplay = 1;
04591          else
04592             parkedplay = 0;
04593       } else if (!strcasecmp(var->name, "xfersound")) {
04594          ast_copy_string(xfersound, var->value, sizeof(xfersound));
04595       } else if (!strcasecmp(var->name, "xferfailsound")) {
04596          ast_copy_string(xferfailsound, var->value, sizeof(xferfailsound));
04597       } else if (!strcasecmp(var->name, "pickupexten")) {
04598          ast_copy_string(pickup_ext, var->value, sizeof(pickup_ext));
04599       } else if (!strcasecmp(var->name, "pickupsound")) {
04600          ast_copy_string(pickupsound, var->value, sizeof(pickupsound));
04601       } else if (!strcasecmp(var->name, "pickupfailsound")) {
04602          ast_copy_string(pickupfailsound, var->value, sizeof(pickupfailsound));
04603       } else if (!strcasecmp(var->name, "comebacktoorigin")) {
04604          comebacktoorigin = ast_true(var->value);
04605       } else if (!strcasecmp(var->name, "parkedmusicclass")) {
04606          ast_copy_string(default_parkinglot->mohclass, var->value, sizeof(default_parkinglot->mohclass));
04607       }
04608    }
04609 
04610    unmap_features();
04611    for (var = ast_variable_browse(cfg, "featuremap"); var; var = var->next) {
04612       if (remap_feature(var->name, var->value))
04613          ast_log(LOG_NOTICE, "Unknown feature '%s'\n", var->name);
04614    }
04615 
04616    /* Map a key combination to an application*/
04617    ast_unregister_features();
04618    for (var = ast_variable_browse(cfg, "applicationmap"); var; var = var->next) {
04619       char *tmp_val = ast_strdupa(var->value);
04620       char *activateon; 
04621       struct ast_call_feature *feature;
04622       AST_DECLARE_APP_ARGS(args,
04623          AST_APP_ARG(exten);
04624          AST_APP_ARG(activatedby);
04625          AST_APP_ARG(app);
04626          AST_APP_ARG(app_args);
04627          AST_APP_ARG(moh_class);
04628       );
04629 
04630       AST_STANDARD_APP_ARGS(args, tmp_val);
04631       if (strchr(args.app, '(')) {
04632          /* New syntax */
04633          args.moh_class = args.app_args;
04634          args.app_args = strchr(args.app, '(');
04635          *args.app_args++ = '\0';
04636          if (args.app_args[strlen(args.app_args) - 1] == ')') {
04637             args.app_args[strlen(args.app_args) - 1] = '\0';
04638          }
04639       }
04640 
04641       activateon = strsep(&args.activatedby, "/"); 
04642 
04643       /*! \todo XXX var_name or app_args ? */
04644       if (ast_strlen_zero(args.app) || ast_strlen_zero(args.exten) || ast_strlen_zero(activateon) || ast_strlen_zero(var->name)) {
04645          ast_log(LOG_NOTICE, "Please check the feature Mapping Syntax, either extension, name, or app aren't provided %s %s %s %s\n",
04646             args.app, args.exten, activateon, var->name);
04647          continue;
04648       }
04649 
04650       AST_RWLIST_RDLOCK(&feature_list);
04651       if ((feature = find_dynamic_feature(var->name))) {
04652          AST_RWLIST_UNLOCK(&feature_list);
04653          ast_log(LOG_WARNING, "Dynamic Feature '%s' specified more than once!\n", var->name);
04654          continue;
04655       }
04656       AST_RWLIST_UNLOCK(&feature_list);
04657             
04658       if (!(feature = ast_calloc(1, sizeof(*feature)))) {
04659          continue;
04660       }
04661 
04662       ast_copy_string(feature->sname, var->name, FEATURE_SNAME_LEN);
04663       ast_copy_string(feature->app, args.app, FEATURE_APP_LEN);
04664       ast_copy_string(feature->exten, args.exten, FEATURE_EXTEN_LEN);
04665       
04666       if (args.app_args) {
04667          ast_copy_string(feature->app_args, args.app_args, FEATURE_APP_ARGS_LEN);
04668       }
04669 
04670       if (args.moh_class) {
04671          ast_copy_string(feature->moh_class, args.moh_class, FEATURE_MOH_LEN);
04672       }
04673 
04674       ast_copy_string(feature->exten, args.exten, sizeof(feature->exten));
04675       feature->operation = feature_exec_app;
04676       ast_set_flag(feature, AST_FEATURE_FLAG_NEEDSDTMF);
04677 
04678       /* Allow caller and calle to be specified for backwards compatability */
04679       if (!strcasecmp(activateon, "self") || !strcasecmp(activateon, "caller"))
04680          ast_set_flag(feature, AST_FEATURE_FLAG_ONSELF);
04681       else if (!strcasecmp(activateon, "peer") || !strcasecmp(activateon, "callee"))
04682          ast_set_flag(feature, AST_FEATURE_FLAG_ONPEER);
04683       else {
04684          ast_log(LOG_NOTICE, "Invalid 'ActivateOn' specification for feature '%s',"
04685             " must be 'self', or 'peer'\n", var->name);
04686          continue;
04687       }
04688 
04689       if (ast_strlen_zero(args.activatedby))
04690          ast_set_flag(feature, AST_FEATURE_FLAG_BYBOTH);
04691       else if (!strcasecmp(args.activatedby, "caller"))
04692          ast_set_flag(feature, AST_FEATURE_FLAG_BYCALLER);
04693       else if (!strcasecmp(args.activatedby, "callee"))
04694          ast_set_flag(feature, AST_FEATURE_FLAG_BYCALLEE);
04695       else if (!strcasecmp(args.activatedby, "both"))
04696          ast_set_flag(feature, AST_FEATURE_FLAG_BYBOTH);
04697       else {
04698          ast_log(LOG_NOTICE, "Invalid 'ActivatedBy' specification for feature '%s',"
04699             " must be 'caller', or 'callee', or 'both'\n", var->name);
04700          continue;
04701       }
04702 
04703       ast_register_feature(feature);
04704 
04705       ast_verb(2, "Mapping Feature '%s' to app '%s(%s)' with code '%s'\n", var->name, args.app, args.app_args, args.exten);
04706    }
04707 
04708    ast_unregister_groups();
04709    AST_RWLIST_WRLOCK(&feature_groups);
04710 
04711    ctg = NULL;
04712    while ((ctg = ast_category_browse(cfg, ctg))) {
04713       /* Is this a parkinglot definition ? */
04714       if (!strncasecmp(ctg, "parkinglot_", strlen("parkinglot_"))) {
04715          ast_debug(2, "Found configuration section %s, assume parking context\n", ctg);
04716          if(!build_parkinglot(ctg, ast_variable_browse(cfg, ctg)))
04717             ast_log(LOG_ERROR, "Could not build parking lot %s. Configuration error.\n", ctg);
04718          else
04719             ast_debug(1, "Configured parking context %s\n", ctg);
04720          continue;   
04721       }
04722       /* No, check if it's a group */
04723       for (i = 0; i < ARRAY_LEN(categories); i++) {
04724          if (!strcasecmp(categories[i], ctg))
04725             break;
04726       }
04727 
04728       if (i < ARRAY_LEN(categories)) 
04729          continue;
04730 
04731       if (!(fg = register_group(ctg)))
04732          continue;
04733 
04734       for (var = ast_variable_browse(cfg, ctg); var; var = var->next) {
04735          struct ast_call_feature *feature;
04736 
04737          AST_RWLIST_RDLOCK(&feature_list);
04738          if (!(feature = find_dynamic_feature(var->name)) && 
04739              !(feature = ast_find_call_feature(var->name))) {
04740             AST_RWLIST_UNLOCK(&feature_list);
04741             ast_log(LOG_WARNING, "Feature '%s' was not found.\n", var->name);
04742             continue;
04743          }
04744          AST_RWLIST_UNLOCK(&feature_list);
04745 
04746          register_group_feature(fg, var->value, feature);
04747       }
04748    }
04749 
04750    AST_RWLIST_UNLOCK(&feature_groups);
04751 
04752    ast_config_destroy(cfg);
04753 
04754    if (!(con = ast_context_find_or_create(NULL, NULL, default_parkinglot->parking_con, registrar))) {
04755       ast_log(LOG_ERROR, "Parking context '%s' does not exist and unable to create\n", default_parkinglot->parking_con);
04756       return -1;
04757    }
04758    res = ast_add_extension2(con, 1, default_parkinglot->parkext, 1, NULL, NULL, parkcall, NULL, NULL, registrar);
04759    if (default_parkinglot->parkaddhints)
04760       park_add_hints(default_parkinglot->parking_con, default_parkinglot->parking_start, default_parkinglot->parking_stop);
04761    if (!res)
04762       notify_metermaids(default_parkinglot->parkext, default_parkinglot->parking_con, AST_DEVICE_INUSE); 
04763    return res;
04764 
04765 }
04766 
04767 /*!
04768  * \brief CLI command to list configured features
04769  * \param e
04770  * \param cmd
04771  * \param a
04772  *
04773  * \retval CLI_SUCCESS on success.
04774  * \retval NULL when tab completion is used.
04775  */
04776 static char *handle_feature_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04777 {
04778    int i;
04779    struct ast_call_feature *feature;
04780    struct ao2_iterator iter;
04781    struct ast_parkinglot *curlot;
04782 #define HFS_FORMAT "%-25s %-7s %-7s\n"
04783 
04784    switch (cmd) {
04785    
04786    case CLI_INIT:
04787       e->command = "features show";
04788       e->usage =
04789          "Usage: features show\n"
04790          "       Lists configured features\n";
04791       return NULL;
04792    case CLI_GENERATE:
04793       return NULL;
04794    }
04795 
04796    ast_cli(a->fd, HFS_FORMAT, "Builtin Feature", "Default", "Current");
04797    ast_cli(a->fd, HFS_FORMAT, "---------------", "-------", "-------");
04798 
04799    ast_cli(a->fd, HFS_FORMAT, "Pickup", "*8", ast_pickup_ext());          /* default hardcoded above, so we'll hardcode it here */
04800 
04801    ast_rwlock_rdlock(&features_lock);
04802    for (i = 0; i < FEATURES_COUNT; i++)
04803       ast_cli(a->fd, HFS_FORMAT, builtin_features[i].fname, builtin_features[i].default_exten, builtin_features[i].exten);
04804    ast_rwlock_unlock(&features_lock);
04805 
04806    ast_cli(a->fd, "\n");
04807    ast_cli(a->fd, HFS_FORMAT, "Dynamic Feature", "Default", "Current");
04808    ast_cli(a->fd, HFS_FORMAT, "---------------", "-------", "-------");
04809    if (AST_RWLIST_EMPTY(&feature_list)) {
04810       ast_cli(a->fd, "(none)\n");
04811    } else {
04812       AST_RWLIST_RDLOCK(&feature_list);
04813       AST_RWLIST_TRAVERSE(&feature_list, feature, feature_entry) {
04814          ast_cli(a->fd, HFS_FORMAT, feature->sname, "no def", feature->exten);
04815       }
04816       AST_RWLIST_UNLOCK(&feature_list);
04817    }
04818 
04819    ast_cli(a->fd, "\nFeature Groups:\n");
04820    ast_cli(a->fd, "---------------\n");
04821    if (AST_RWLIST_EMPTY(&feature_groups)) {
04822       ast_cli(a->fd, "(none)\n");
04823    } else {
04824       struct feature_group *fg;
04825       struct feature_group_exten *fge;
04826 
04827       AST_RWLIST_RDLOCK(&feature_groups);
04828       AST_RWLIST_TRAVERSE(&feature_groups, fg, entry) {
04829          ast_cli(a->fd, "===> Group: %s\n", fg->gname);
04830          AST_LIST_TRAVERSE(&fg->features, fge, entry) {
04831             ast_cli(a->fd, "===> --> %s (%s)\n", fge->feature->sname, fge->exten);
04832          }
04833       }
04834       AST_RWLIST_UNLOCK(&feature_groups);
04835    }
04836 
04837    iter = ao2_iterator_init(parkinglots, 0);
04838    while ((curlot = ao2_iterator_next(&iter))) {
04839       ast_cli(a->fd, "\nCall parking (Parking lot: %s)\n", curlot->name);
04840       ast_cli(a->fd, "------------\n");
04841       ast_cli(a->fd,"%-22s:      %s\n", "Parking extension", curlot->parkext);
04842       ast_cli(a->fd,"%-22s:      %s\n", "Parking context", curlot->parking_con);
04843       ast_cli(a->fd,"%-22s:      %d-%d\n", "Parked call extensions", curlot->parking_start, curlot->parking_stop);
04844       ast_cli(a->fd,"%-22s:      %d\n", "Parkingtime", curlot->parkingtime);
04845       ast_cli(a->fd,"%-22s:      %s\n", "MusicOnHold class", curlot->mohclass);
04846       ast_cli(a->fd,"\n");
04847       ao2_ref(curlot, -1);
04848    }
04849    ao2_iterator_destroy(&iter);
04850 
04851    return CLI_SUCCESS;
04852 }
04853 
04854 static int parkinglot_markall_cb(void *obj, void *arg, int flags)
04855 {
04856    struct ast_parkinglot *parkinglot = obj;
04857    parkinglot->the_mark = 1;
04858    return 0;
04859 }
04860 
04861 static int parkinglot_is_marked_cb(void *obj, void *arg, int flags)
04862 {
04863    struct ast_parkinglot *parkinglot = obj;
04864    return parkinglot->the_mark ? CMP_MATCH : 0;
04865 }
04866 
04867 int ast_features_reload(void)
04868 {
04869    int res;
04870 
04871    ao2_t_callback(parkinglots, OBJ_NODATA, parkinglot_markall_cb, NULL, "callback to mark all parkinglots");
04872    res = load_config(); /* Reload configuration */
04873    ao2_t_callback(parkinglots, OBJ_NODATA | OBJ_UNLINK, parkinglot_is_marked_cb, NULL, "callback to remove all marked parkinglots");
04874    
04875    return res;
04876 }
04877 
04878 static char *handle_features_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04879 {
04880    switch (cmd) { 
04881    case CLI_INIT:
04882       e->command = "features reload";
04883       e->usage =
04884          "Usage: features reload\n"
04885          "       Reloads configured call features from features.conf\n";
04886       return NULL;
04887    case CLI_GENERATE:
04888       return NULL;
04889    }
04890    ast_features_reload();
04891 
04892    return CLI_SUCCESS;
04893 }
04894 
04895 /*!
04896  * \brief Actual bridge
04897  * \param chan
04898  * \param tmpchan
04899  * 
04900  * Stop hold music, lock both channels, masq channels,
04901  * after bridge return channel to next priority.
04902 */
04903 static void do_bridge_masquerade(struct ast_channel *chan, struct ast_channel *tmpchan)
04904 {
04905    ast_moh_stop(chan);
04906    ast_channel_lock_both(chan, tmpchan);
04907    ast_setstate(tmpchan, chan->_state);
04908    tmpchan->readformat = chan->readformat;
04909    tmpchan->writeformat = chan->writeformat;
04910    ast_channel_masquerade(tmpchan, chan);
04911    ast_channel_unlock(chan);
04912    ast_channel_unlock(tmpchan);
04913 
04914    /* must be done without any channel locks held */
04915    ast_do_masquerade(tmpchan);
04916 
04917    /* when returning from bridge, the channel will continue at the next priority */
04918    ast_explicit_goto(tmpchan, chan->context, chan->exten, chan->priority + 1);
04919 }
04920 
04921 /*!
04922  * \brief Bridge channels together
04923  * \param s
04924  * \param m
04925  * 
04926  * Make sure valid channels were specified, 
04927  * send errors if any of the channels could not be found/locked, answer channels if needed,
04928  * create the placeholder channels and grab the other channels 
04929  * make the channels compatible, send error if we fail doing so 
04930  * setup the bridge thread object and start the bridge.
04931  * 
04932  * \retval 0 on success or on incorrect use.
04933  * \retval 1 on failure to bridge channels.
04934 */
04935 static int action_bridge(struct mansession *s, const struct message *m)
04936 {
04937    const char *channela = astman_get_header(m, "Channel1");
04938    const char *channelb = astman_get_header(m, "Channel2");
04939    const char *playtone = astman_get_header(m, "Tone");
04940    struct ast_channel *chana = NULL, *chanb = NULL, *chans[2];
04941    struct ast_channel *tmpchana = NULL, *tmpchanb = NULL;
04942    struct ast_bridge_thread_obj *tobj = NULL;
04943 
04944    /* make sure valid channels were specified */
04945    if (ast_strlen_zero(channela) || ast_strlen_zero(channelb)) {
04946       astman_send_error(s, m, "Missing channel parameter in request");
04947       return 0;
04948    }
04949 
04950    /* Start with chana */
04951    chana = ast_channel_get_by_name_prefix(channela, strlen(channela));
04952 
04953    /* send errors if any of the channels could not be found/locked */
04954    if (!chana) {
04955       char buf[256];
04956       snprintf(buf, sizeof(buf), "Channel1 does not exists: %s", channela);
04957       astman_send_error(s, m, buf);
04958       return 0;
04959    }
04960 
04961    /* Answer the channels if needed */
04962    if (chana->_state != AST_STATE_UP)
04963       ast_answer(chana);
04964 
04965    /* create the placeholder channels and grab the other channels */
04966    if (!(tmpchana = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL, 
04967       NULL, NULL, chana->linkedid, 0, "Bridge/%s", chana->name))) {
04968       astman_send_error(s, m, "Unable to create temporary channel!");
04969       chana = ast_channel_unref(chana);
04970       return 1;
04971    }
04972 
04973    do_bridge_masquerade(chana, tmpchana);
04974 
04975    chana = ast_channel_unref(chana);
04976 
04977    /* now do chanb */
04978    chanb = ast_channel_get_by_name_prefix(channelb, strlen(channelb));
04979    /* send errors if any of the channels could not be found/locked */
04980    if (!chanb) {
04981       char buf[256];
04982       snprintf(buf, sizeof(buf), "Channel2 does not exists: %s", channelb);
04983       ast_hangup(tmpchana);
04984       astman_send_error(s, m, buf);
04985       return 0;
04986    }
04987 
04988    /* Answer the channels if needed */
04989    if (chanb->_state != AST_STATE_UP)
04990       ast_answer(chanb);
04991 
04992    /* create the placeholder channels and grab the other channels */
04993    if (!(tmpchanb = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL, 
04994       NULL, NULL, chanb->linkedid, 0, "Bridge/%s", chanb->name))) {
04995       astman_send_error(s, m, "Unable to create temporary channels!");
04996       ast_hangup(tmpchana);
04997       chanb = ast_channel_unref(chanb);
04998       return 1;
04999    }
05000 
05001    do_bridge_masquerade(chanb, tmpchanb);
05002 
05003    chanb = ast_channel_unref(chanb);
05004 
05005    /* make the channels compatible, send error if we fail doing so */
05006    if (ast_channel_make_compatible(tmpchana, tmpchanb)) {
05007       ast_log(LOG_WARNING, "Could not make channels %s and %s compatible for manager bridge\n", tmpchana->name, tmpchanb->name);
05008       astman_send_error(s, m, "Could not make channels compatible for manager bridge");
05009       ast_hangup(tmpchana);
05010       ast_hangup(tmpchanb);
05011       return 1;
05012    }
05013 
05014    /* setup the bridge thread object and start the bridge */
05015    if (!(tobj = ast_calloc(1, sizeof(*tobj)))) {
05016       ast_log(LOG_WARNING, "Unable to spawn a new bridge thread on %s and %s: %s\n", tmpchana->name, tmpchanb->name, strerror(errno));
05017       astman_send_error(s, m, "Unable to spawn a new bridge thread");
05018       ast_hangup(tmpchana);
05019       ast_hangup(tmpchanb);
05020       return 1;
05021    }
05022 
05023    tobj->chan = tmpchana;
05024    tobj->peer = tmpchanb;
05025    tobj->return_to_pbx = 1;
05026 
05027    if (ast_true(playtone)) {
05028       if (!ast_strlen_zero(xfersound) && !ast_streamfile(tmpchanb, xfersound, tmpchanb->language)) {
05029          if (ast_waitstream(tmpchanb, "") < 0)
05030             ast_log(LOG_WARNING, "Failed to play a courtesy tone on chan %s\n", tmpchanb->name);
05031       }
05032    }
05033 
05034    chans[0] = tmpchana;
05035    chans[1] = tmpchanb;
05036 
05037    ast_manager_event_multichan(EVENT_FLAG_CALL, "BridgeAction", 2, chans,
05038             "Response: Success\r\n"
05039             "Channel1: %s\r\n"
05040             "Channel2: %s\r\n", tmpchana->name, tmpchanb->name);
05041 
05042    bridge_call_thread_launch(tobj);
05043 
05044    astman_send_ack(s, m, "Launched bridge thread with success");
05045 
05046    return 0;
05047 }
05048 
05049 /*!
05050  * \brief CLI command to list parked calls
05051  * \param e 
05052  * \param cmd
05053  * \param a
05054  *  
05055  * Check right usage, lock parking lot, display parked calls, unlock parking lot list.
05056  * \retval CLI_SUCCESS on success.
05057  * \retval CLI_SHOWUSAGE on incorrect number of arguments.
05058  * \retval NULL when tab completion is used.
05059 */
05060 static char *handle_parkedcalls(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
05061 {
05062    struct parkeduser *cur;
05063    int numparked = 0;
05064    struct ao2_iterator iter;
05065    struct ast_parkinglot *curlot;
05066 
05067    switch (cmd) {
05068    case CLI_INIT:
05069       e->command = "parkedcalls show";
05070       e->usage =
05071          "Usage: parkedcalls show\n"
05072          "       List currently parked calls\n";
05073       return NULL;
05074    case CLI_GENERATE:
05075       return NULL;
05076    }
05077 
05078    if (a->argc > e->args)
05079       return CLI_SHOWUSAGE;
05080 
05081    ast_cli(a->fd, "%4s %25s (%-15s %-12s %-4s) %-6s \n", "Num", "Channel"
05082       , "Context", "Extension", "Pri", "Timeout");
05083 
05084    iter = ao2_iterator_init(parkinglots, 0);
05085    while ((curlot = ao2_iterator_next(&iter))) {
05086       int lotparked = 0;
05087       /* subtract ref for iterator and for configured parking lot */
05088       ast_cli(a->fd, "*** Parking lot: %s (%d)\n", curlot->name, ao2_ref(curlot, 0) - 2);
05089 
05090       AST_LIST_LOCK(&curlot->parkings);
05091       AST_LIST_TRAVERSE(&curlot->parkings, cur, list) {
05092          ast_cli(a->fd, "%-10.10s %25s (%-15s %-12s %-4d) %6lds\n"
05093             ,cur->parkingexten, cur->chan->name, cur->context, cur->exten
05094             ,cur->priority,
05095             (long)(cur->start.tv_sec + (cur->parkingtime/1000) - time(NULL)) );
05096          numparked++;
05097          numparked += lotparked;
05098       }
05099       AST_LIST_UNLOCK(&curlot->parkings);
05100       if (lotparked)
05101          ast_cli(a->fd, "   %d parked call%s in parking lot %s\n", lotparked, ESS(lotparked), curlot->name);
05102 
05103       ao2_ref(curlot, -1);
05104    }
05105 
05106    ast_cli(a->fd, "---\n%d parked call%s in total.\n", numparked, ESS(numparked));
05107 
05108    return CLI_SUCCESS;
05109 }
05110 
05111 static struct ast_cli_entry cli_features[] = {
05112    AST_CLI_DEFINE(handle_feature_show, "Lists configured features"),
05113    AST_CLI_DEFINE(handle_features_reload, "Reloads configured features"),
05114    AST_CLI_DEFINE(handle_parkedcalls, "List currently parked calls"),
05115 };
05116 
05117 /*! 
05118  * \brief Dump parking lot status
05119  * \param s
05120  * \param m
05121  * 
05122  * Lock parking lot, iterate list and append parked calls status, unlock parking lot.
05123  * \return Always RESULT_SUCCESS 
05124 */
05125 static int manager_parking_status(struct mansession *s, const struct message *m)
05126 {
05127    struct parkeduser *cur;
05128    const char *id = astman_get_header(m, "ActionID");
05129    char idText[256] = "";
05130    struct ao2_iterator iter;
05131    struct ast_parkinglot *curlot;
05132 
05133    if (!ast_strlen_zero(id))
05134       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
05135 
05136    astman_send_ack(s, m, "Parked calls will follow");
05137 
05138    iter = ao2_iterator_init(parkinglots, 0);
05139    while ((curlot = ao2_iterator_next(&iter))) {
05140 
05141       AST_LIST_LOCK(&curlot->parkings);
05142       AST_LIST_TRAVERSE(&curlot->parkings, cur, list) {
05143          astman_append(s, "Event: ParkedCall\r\n"
05144             "Exten: %d\r\n"
05145             "Channel: %s\r\n"
05146             "From: %s\r\n"
05147             "Timeout: %ld\r\n"
05148             "CallerIDNum: %s\r\n"
05149             "CallerIDName: %s\r\n"
05150             "%s"
05151             "\r\n",
05152             cur->parkingnum, cur->chan->name, cur->peername,
05153             (long) cur->start.tv_sec + (long) (cur->parkingtime / 1000) - (long) time(NULL),
05154             S_COR(cur->chan->caller.id.number.valid, cur->chan->caller.id.number.str, ""),   /* XXX in other places it is <unknown> */
05155             S_COR(cur->chan->caller.id.name.valid, cur->chan->caller.id.name.str, ""),
05156             idText);
05157       }
05158       AST_LIST_UNLOCK(&curlot->parkings);
05159       ao2_ref(curlot, -1);
05160    }
05161 
05162    astman_append(s,
05163       "Event: ParkedCallsComplete\r\n"
05164       "%s"
05165       "\r\n",idText);
05166 
05167 
05168    return RESULT_SUCCESS;
05169 }
05170 
05171 /*!
05172  * \brief Create manager event for parked calls
05173  * \param s
05174  * \param m
05175  *
05176  * Get channels involved in park, create event.
05177  * \return Always 0
05178 */
05179 static int manager_park(struct mansession *s, const struct message *m)
05180 {
05181    const char *channel = astman_get_header(m, "Channel");
05182    const char *channel2 = astman_get_header(m, "Channel2");
05183    const char *timeout = astman_get_header(m, "Timeout");
05184    const char *parkinglotname = astman_get_header(m, "Parkinglot");
05185    char buf[BUFSIZ];
05186    int res = 0;
05187    struct ast_channel *ch1, *ch2;
05188    struct ast_park_call_args args = {0,};
05189 
05190    if (ast_strlen_zero(channel)) {
05191       astman_send_error(s, m, "Channel not specified");
05192       return 0;
05193    }
05194 
05195    if (ast_strlen_zero(channel2)) {
05196       astman_send_error(s, m, "Channel2 not specified");
05197       return 0;
05198    }
05199 
05200    if (!(ch1 = ast_channel_get_by_name(channel))) {
05201       snprintf(buf, sizeof(buf), "Channel does not exist: %s", channel);
05202       astman_send_error(s, m, buf);
05203       return 0;
05204    }
05205 
05206    if (!(ch2 = ast_channel_get_by_name(channel2))) {
05207       snprintf(buf, sizeof(buf), "Channel does not exist: %s", channel2);
05208       astman_send_error(s, m, buf);
05209       ast_channel_unref(ch1);
05210       return 0;
05211    }
05212 
05213    if (!ast_strlen_zero(timeout)) {
05214       sscanf(timeout, "%30d", &args.timeout);
05215    }
05216    if (!ast_strlen_zero(parkinglotname)) {
05217       args.parkinglot = find_parkinglot(parkinglotname);
05218    }
05219 
05220    ast_channel_lock(ch1);
05221    while (ast_channel_trylock(ch2)) {
05222       CHANNEL_DEADLOCK_AVOIDANCE(ch1);
05223    }
05224 
05225    res = masq_park_call(ch1, ch2, 0, NULL, 0, &args);
05226    if (!res) {
05227       ast_softhangup(ch2, AST_SOFTHANGUP_EXPLICIT);
05228       astman_send_ack(s, m, "Park successful");
05229    } else {
05230       astman_send_error(s, m, "Park failure");
05231    }
05232 
05233    ast_channel_unlock(ch1);
05234    ast_channel_unlock(ch2);
05235 
05236    ch1 = ast_channel_unref(ch1);
05237    ch2 = ast_channel_unref(ch2);
05238 
05239    return 0;
05240 }
05241 
05242 static int find_channel_by_group(void *obj, void *arg, void *data, int flags)
05243 {
05244    struct ast_channel *c = data;
05245    struct ast_channel *chan = obj;
05246 
05247    int i = !chan->pbx &&
05248       /* Accessing 'chan' here is safe without locking, because there is no way for
05249          the channel do disappear from under us at this point.  pickupgroup *could*
05250          change while we're here, but that isn't a problem. */
05251       (c != chan) &&
05252       (chan->pickupgroup & c->callgroup) &&
05253       ((chan->_state == AST_STATE_RINGING) || (chan->_state == AST_STATE_RING));
05254 
05255    return i ? CMP_MATCH | CMP_STOP : 0;
05256 }
05257 
05258 /*!
05259  * \brief Pickup a call
05260  * \param chan channel that initiated pickup.
05261  *
05262  * Walk list of channels, checking it is not itself, channel is pbx one,
05263  * check that the callgroup for both channels are the same and the channel is ringing.
05264  * Answer calling channel, flag channel as answered on queue, masq channels together.
05265 */
05266 int ast_pickup_call(struct ast_channel *chan)
05267 {
05268    struct ast_channel *cur, *chans[2] = { chan, };
05269    struct ast_party_connected_line connected_caller;
05270    int res;
05271    const char *chan_name;
05272    const char *cur_name;
05273 
05274    if (!(cur = ast_channel_callback(find_channel_by_group, NULL, chan, 0))) {
05275       ast_debug(1, "No call pickup possible...\n");
05276       if (!ast_strlen_zero(pickupfailsound)) {
05277          ast_stream_and_wait(chan, pickupfailsound, "");
05278       }
05279       return -1;
05280    }
05281 
05282    chans[1] = cur;
05283 
05284    ast_channel_lock_both(cur, chan);
05285 
05286    cur_name = ast_strdupa(cur->name);
05287    chan_name = ast_strdupa(chan->name);
05288 
05289    ast_debug(1, "Call pickup on chan '%s' by '%s'\n", cur_name, chan_name);
05290 
05291    connected_caller = cur->connected;
05292    connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
05293    if (ast_channel_connected_line_macro(NULL, chan, &connected_caller, 0, 0)) {
05294       ast_channel_update_connected_line(chan, &connected_caller, NULL);
05295    }
05296 
05297    ast_party_connected_line_collect_caller(&connected_caller, &chan->caller);
05298    connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
05299    ast_channel_queue_connected_line_update(chan, &connected_caller, NULL);
05300 
05301    ast_channel_unlock(cur);
05302    ast_channel_unlock(chan);
05303 
05304    if (ast_answer(chan)) {
05305       ast_log(LOG_WARNING, "Unable to answer '%s'\n", chan_name);
05306    }
05307 
05308    if (ast_queue_control(chan, AST_CONTROL_ANSWER)) {
05309       ast_log(LOG_WARNING, "Unable to queue answer on '%s'\n", chan_name);
05310    }
05311 
05312    if ((res = ast_channel_masquerade(cur, chan))) {
05313       ast_log(LOG_WARNING, "Unable to masquerade '%s' into '%s'\n", chan_name, cur_name);
05314    }
05315 
05316    if (!ast_strlen_zero(pickupsound)) {
05317       ast_stream_and_wait(cur, pickupsound, "");
05318    }
05319 
05320    /* If you want UniqueIDs, set channelvars in manager.conf to CHANNEL(uniqueid) */
05321    ast_manager_event_multichan(EVENT_FLAG_CALL, "Pickup", 2, chans,
05322       "Channel: %s\r\nTargetChannel: %s\r\n", chan->name, cur->name);
05323 
05324    cur = ast_channel_unref(cur);
05325 
05326    return res;
05327 }
05328 
05329 static char *app_bridge = "Bridge";
05330 
05331 enum {
05332    BRIDGE_OPT_PLAYTONE = (1 << 0),
05333    OPT_CALLEE_HANGUP =  (1 << 1),
05334    OPT_CALLER_HANGUP =  (1 << 2),
05335    OPT_DURATION_LIMIT = (1 << 3),
05336    OPT_DURATION_STOP =  (1 << 4),
05337    OPT_CALLEE_TRANSFER = (1 << 5),
05338    OPT_CALLER_TRANSFER = (1 << 6),
05339    OPT_CALLEE_MONITOR = (1 << 7),
05340    OPT_CALLER_MONITOR = (1 << 8),
05341    OPT_CALLEE_PARK = (1 << 9),
05342    OPT_CALLER_PARK = (1 << 10),
05343    OPT_CALLEE_KILL = (1 << 11),
05344 };
05345  
05346 enum {
05347    OPT_ARG_DURATION_LIMIT = 0,
05348    OPT_ARG_DURATION_STOP,
05349    /* note: this entry _MUST_ be the last one in the enum */
05350    OPT_ARG_ARRAY_SIZE,
05351 };
05352 
05353 AST_APP_OPTIONS(bridge_exec_options, BEGIN_OPTIONS
05354    AST_APP_OPTION('p', BRIDGE_OPT_PLAYTONE),
05355    AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
05356    AST_APP_OPTION('H', OPT_CALLER_HANGUP),
05357    AST_APP_OPTION('k', OPT_CALLEE_PARK),
05358    AST_APP_OPTION('K', OPT_CALLER_PARK),
05359    AST_APP_OPTION_ARG('L', OPT_DURATION_LIMIT, OPT_ARG_DURATION_LIMIT),
05360    AST_APP_OPTION_ARG('S', OPT_DURATION_STOP, OPT_ARG_DURATION_STOP),
05361    AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
05362    AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
05363    AST_APP_OPTION('w', OPT_CALLEE_MONITOR),
05364    AST_APP_OPTION('W', OPT_CALLER_MONITOR),
05365    AST_APP_OPTION('x', OPT_CALLEE_KILL),
05366 END_OPTIONS );
05367 
05368 int ast_bridge_timelimit(struct ast_channel *chan, struct ast_bridge_config *config,
05369    char *parse, struct timeval *calldurationlimit)
05370 {
05371    char *stringp = ast_strdupa(parse);
05372    char *limit_str, *warning_str, *warnfreq_str;
05373    const char *var;
05374    int play_to_caller = 0, play_to_callee = 0;
05375    int delta;
05376 
05377    limit_str = strsep(&stringp, ":");
05378    warning_str = strsep(&stringp, ":");
05379    warnfreq_str = strsep(&stringp, ":");
05380 
05381    config->timelimit = atol(limit_str);
05382    if (warning_str)
05383       config->play_warning = atol(warning_str);
05384    if (warnfreq_str)
05385       config->warning_freq = atol(warnfreq_str);
05386 
05387    if (!config->timelimit) {
05388       ast_log(LOG_WARNING, "Bridge does not accept L(%s), hanging up.\n", limit_str);
05389       config->timelimit = config->play_warning = config->warning_freq = 0;
05390       config->warning_sound = NULL;
05391       return -1; /* error */
05392    } else if ( (delta = config->play_warning - config->timelimit) > 0) {
05393       int w = config->warning_freq;
05394 
05395       /* If the first warning is requested _after_ the entire call would end,
05396          and no warning frequency is requested, then turn off the warning. If
05397          a warning frequency is requested, reduce the 'first warning' time by
05398          that frequency until it falls within the call's total time limit.
05399          Graphically:
05400               timelim->|    delta        |<-playwarning
05401          0__________________|_________________|
05402                 | w  |    |    |    |
05403 
05404          so the number of intervals to cut is 1+(delta-1)/w
05405       */
05406 
05407       if (w == 0) {
05408          config->play_warning = 0;
05409       } else {
05410          config->play_warning -= w * ( 1 + (delta-1)/w );
05411          if (config->play_warning < 1)
05412             config->play_warning = config->warning_freq = 0;
05413       }
05414    }
05415    
05416    ast_channel_lock(chan);
05417 
05418    var = pbx_builtin_getvar_helper(chan, "LIMIT_PLAYAUDIO_CALLER");
05419    play_to_caller = var ? ast_true(var) : 1;
05420 
05421    var = pbx_builtin_getvar_helper(chan, "LIMIT_PLAYAUDIO_CALLEE");
05422    play_to_callee = var ? ast_true(var) : 0;
05423 
05424    if (!play_to_caller && !play_to_callee)
05425       play_to_caller = 1;
05426 
05427    var = pbx_builtin_getvar_helper(chan, "LIMIT_WARNING_FILE");
05428    config->warning_sound = !ast_strlen_zero(var) ? ast_strdup(var) : ast_strdup("timeleft");
05429 
05430    /* The code looking at config wants a NULL, not just "", to decide
05431     * that the message should not be played, so we replace "" with NULL.
05432     * Note, pbx_builtin_getvar_helper _can_ return NULL if the variable is
05433     * not found.
05434     */
05435 
05436    var = pbx_builtin_getvar_helper(chan, "LIMIT_TIMEOUT_FILE");
05437    config->end_sound = !ast_strlen_zero(var) ? ast_strdup(var) : NULL;
05438 
05439    var = pbx_builtin_getvar_helper(chan, "LIMIT_CONNECT_FILE");
05440    config->start_sound = !ast_strlen_zero(var) ? ast_strdup(var) : NULL;
05441 
05442    ast_channel_unlock(chan);
05443 
05444    /* undo effect of S(x) in case they are both used */
05445    calldurationlimit->tv_sec = 0;
05446    calldurationlimit->tv_usec = 0;
05447 
05448    /* more efficient to do it like S(x) does since no advanced opts */
05449    if (!config->play_warning && !config->start_sound && !config->end_sound && config->timelimit) {
05450       calldurationlimit->tv_sec = config->timelimit / 1000;
05451       calldurationlimit->tv_usec = (config->timelimit % 1000) * 1000;
05452       ast_verb(3, "Setting call duration limit to %.3lf seconds.\n",
05453          calldurationlimit->tv_sec + calldurationlimit->tv_usec / 1000000.0);
05454       config->timelimit = play_to_caller = play_to_callee =
05455       config->play_warning = config->warning_freq = 0;
05456    } else {
05457       ast_verb(4, "Limit Data for this call:\n");
05458       ast_verb(4, "timelimit      = %ld ms (%.3lf s)\n", config->timelimit, config->timelimit / 1000.0);
05459       ast_verb(4, "play_warning   = %ld ms (%.3lf s)\n", config->play_warning, config->play_warning / 1000.0);
05460       ast_verb(4, "play_to_caller = %s\n", play_to_caller ? "yes" : "no");
05461       ast_verb(4, "play_to_callee = %s\n", play_to_callee ? "yes" : "no");
05462       ast_verb(4, "warning_freq   = %ld ms (%.3lf s)\n", config->warning_freq, config->warning_freq / 1000.0);
05463       ast_verb(4, "start_sound    = %s\n", S_OR(config->start_sound, ""));
05464       ast_verb(4, "warning_sound  = %s\n", config->warning_sound);
05465       ast_verb(4, "end_sound      = %s\n", S_OR(config->end_sound, ""));
05466    }
05467    if (play_to_caller)
05468       ast_set_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING);
05469    if (play_to_callee)
05470       ast_set_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING);
05471    return 0;
05472 }
05473 
05474 
05475 /*!
05476  * \brief Bridge channels
05477  * \param chan
05478  * \param data channel to bridge with.
05479  * 
05480  * Split data, check we aren't bridging with ourself, check valid channel,
05481  * answer call if not already, check compatible channels, setup bridge config
05482  * now bridge call, if transfered party hangs up return to PBX extension.
05483 */
05484 static int bridge_exec(struct ast_channel *chan, const char *data)
05485 {
05486    struct ast_channel *current_dest_chan, *final_dest_chan, *chans[2];
05487    char *tmp_data  = NULL;
05488    struct ast_flags opts = { 0, };
05489    struct ast_bridge_config bconfig = { { 0, }, };
05490    char *opt_args[OPT_ARG_ARRAY_SIZE];
05491    struct timeval calldurationlimit = { 0, };
05492 
05493    AST_DECLARE_APP_ARGS(args,
05494       AST_APP_ARG(dest_chan);
05495       AST_APP_ARG(options);
05496    );
05497    
05498    if (ast_strlen_zero(data)) {
05499       ast_log(LOG_WARNING, "Bridge require at least 1 argument specifying the other end of the bridge\n");
05500       return -1;
05501    }
05502 
05503    tmp_data = ast_strdupa(data);
05504    AST_STANDARD_APP_ARGS(args, tmp_data);
05505    if (!ast_strlen_zero(args.options))
05506       ast_app_parse_options(bridge_exec_options, &opts, opt_args, args.options);
05507 
05508    /* avoid bridge with ourselves */
05509    if (!strcmp(chan->name, args.dest_chan)) {
05510       ast_log(LOG_WARNING, "Unable to bridge channel %s with itself\n", chan->name);
05511       ast_manager_event(chan, EVENT_FLAG_CALL, "BridgeExec",
05512                "Response: Failed\r\n"
05513                "Reason: Unable to bridge channel to itself\r\n"
05514                "Channel1: %s\r\n"
05515                "Channel2: %s\r\n",
05516                chan->name, args.dest_chan);
05517       pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "LOOP");
05518       return 0;
05519    }
05520 
05521    /* make sure we have a valid end point */
05522    if (!(current_dest_chan = ast_channel_get_by_name_prefix(args.dest_chan,
05523          strlen(args.dest_chan)))) {
05524       ast_log(LOG_WARNING, "Bridge failed because channel %s does not exists or we "
05525          "cannot get its lock\n", args.dest_chan);
05526       ast_manager_event(chan, EVENT_FLAG_CALL, "BridgeExec",
05527                "Response: Failed\r\n"
05528                "Reason: Cannot grab end point\r\n"
05529                "Channel1: %s\r\n"
05530                "Channel2: %s\r\n", chan->name, args.dest_chan);
05531       pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "NONEXISTENT");
05532       return 0;
05533    }
05534 
05535    /* answer the channel if needed */
05536    if (current_dest_chan->_state != AST_STATE_UP) {
05537       ast_answer(current_dest_chan);
05538    }
05539 
05540    /* try to allocate a place holder where current_dest_chan will be placed */
05541    if (!(final_dest_chan = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL, 
05542       NULL, NULL, current_dest_chan->linkedid, 0, "Bridge/%s", current_dest_chan->name))) {
05543       ast_log(LOG_WARNING, "Cannot create placeholder channel for chan %s\n", args.dest_chan);
05544       ast_manager_event(chan, EVENT_FLAG_CALL, "BridgeExec",
05545                "Response: Failed\r\n"
05546                "Reason: cannot create placeholder\r\n"
05547                "Channel1: %s\r\n"
05548                "Channel2: %s\r\n", chan->name, args.dest_chan);
05549    }
05550 
05551    ast_channel_unlock(current_dest_chan);
05552 
05553    do_bridge_masquerade(current_dest_chan, final_dest_chan);
05554 
05555    chans[0] = current_dest_chan;
05556    chans[1] = final_dest_chan;
05557 
05558    /* now current_dest_chan is a ZOMBIE and with softhangup set to 1 and final_dest_chan is our end point */
05559    /* try to make compatible, send error if we fail */
05560    if (ast_channel_make_compatible(chan, final_dest_chan) < 0) {
05561       ast_log(LOG_WARNING, "Could not make channels %s and %s compatible for bridge\n", chan->name, final_dest_chan->name);
05562       ast_manager_event_multichan(EVENT_FLAG_CALL, "BridgeExec", 2, chans,
05563                "Response: Failed\r\n"
05564                "Reason: Could not make channels compatible for bridge\r\n"
05565                "Channel1: %s\r\n"
05566                "Channel2: %s\r\n", chan->name, final_dest_chan->name);
05567       ast_hangup(final_dest_chan); /* may be we should return this channel to the PBX? */
05568       pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "INCOMPATIBLE");
05569       current_dest_chan = ast_channel_unref(current_dest_chan);
05570       return 0;
05571    }
05572 
05573    /* Report that the bridge will be successfull */
05574    ast_manager_event_multichan(EVENT_FLAG_CALL, "BridgeExec", 2, chans,
05575             "Response: Success\r\n"
05576             "Channel1: %s\r\n"
05577             "Channel2: %s\r\n", chan->name, final_dest_chan->name);
05578 
05579    /* we have 2 valid channels to bridge, now it is just a matter of setting up the bridge config and starting the bridge */  
05580    if (ast_test_flag(&opts, BRIDGE_OPT_PLAYTONE) && !ast_strlen_zero(xfersound)) {
05581       if (!ast_streamfile(final_dest_chan, xfersound, final_dest_chan->language)) {
05582          if (ast_waitstream(final_dest_chan, "") < 0)
05583             ast_log(LOG_WARNING, "Failed to play courtesy tone on %s\n", final_dest_chan->name);
05584       }
05585    }
05586    
05587    current_dest_chan = ast_channel_unref(current_dest_chan);
05588    
05589    if (ast_test_flag(&opts, OPT_DURATION_LIMIT) && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_LIMIT])) {
05590       if (ast_bridge_timelimit(chan, &bconfig, opt_args[OPT_ARG_DURATION_LIMIT], &calldurationlimit))
05591          goto done;
05592    }
05593 
05594    if (ast_test_flag(&opts, OPT_CALLEE_TRANSFER))
05595       ast_set_flag(&(bconfig.features_callee), AST_FEATURE_REDIRECT);
05596    if (ast_test_flag(&opts, OPT_CALLER_TRANSFER))
05597       ast_set_flag(&(bconfig.features_caller), AST_FEATURE_REDIRECT);
05598    if (ast_test_flag(&opts, OPT_CALLEE_HANGUP))
05599       ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
05600    if (ast_test_flag(&opts, OPT_CALLER_HANGUP))
05601       ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
05602    if (ast_test_flag(&opts, OPT_CALLEE_MONITOR))
05603       ast_set_flag(&(bconfig.features_callee), AST_FEATURE_AUTOMON);
05604    if (ast_test_flag(&opts, OPT_CALLER_MONITOR)) 
05605       ast_set_flag(&(bconfig.features_caller), AST_FEATURE_AUTOMON);
05606    if (ast_test_flag(&opts, OPT_CALLEE_PARK))
05607       ast_set_flag(&(bconfig.features_callee), AST_FEATURE_PARKCALL);
05608    if (ast_test_flag(&opts, OPT_CALLER_PARK))
05609       ast_set_flag(&(bconfig.features_caller), AST_FEATURE_PARKCALL);
05610 
05611    ast_bridge_call(chan, final_dest_chan, &bconfig);
05612 
05613    /* the bridge has ended, set BRIDGERESULT to SUCCESS. If the other channel has not been hung up, return it to the PBX */
05614    pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "SUCCESS");
05615    if (!ast_check_hangup(final_dest_chan) && !ast_test_flag(&opts, OPT_CALLEE_KILL)) {
05616       ast_debug(1, "starting new PBX in %s,%s,%d for chan %s\n", 
05617          final_dest_chan->context, final_dest_chan->exten, 
05618          final_dest_chan->priority, final_dest_chan->name);
05619 
05620       if (ast_pbx_start(final_dest_chan) != AST_PBX_SUCCESS) {
05621          ast_log(LOG_WARNING, "FAILED continuing PBX on dest chan %s\n", final_dest_chan->name);
05622          ast_hangup(final_dest_chan);
05623       } else
05624          ast_debug(1, "SUCCESS continuing PBX on chan %s\n", final_dest_chan->name);
05625    } else {
05626       ast_debug(1, "hangup chan %s since the other endpoint has hung up or the x flag was passed\n", final_dest_chan->name);
05627       ast_hangup(final_dest_chan);
05628    }
05629 done:
05630    if (bconfig.warning_sound) {
05631       ast_free((char *)bconfig.warning_sound);
05632    }
05633    if (bconfig.end_sound) {
05634       ast_free((char *)bconfig.end_sound);
05635    }
05636    if (bconfig.start_sound) {
05637       ast_free((char *)bconfig.start_sound);
05638    }
05639 
05640    return 0;
05641 }
05642 
05643 int ast_features_init(void)
05644 {
05645    int res;
05646 
05647    ast_register_application2(app_bridge, bridge_exec, NULL, NULL, NULL);
05648 
05649    parkinglots = ao2_container_alloc(7, parkinglot_hash_cb, parkinglot_cmp_cb);
05650 
05651    if ((res = load_config()))
05652       return res;
05653    ast_cli_register_multiple(cli_features, ARRAY_LEN(cli_features));
05654    ast_pthread_create(&parking_thread, NULL, do_parking_thread, NULL);
05655    res = ast_register_application2(parkedcall, park_exec, NULL, NULL, NULL);
05656    if (!res)
05657       res = ast_register_application2(parkcall, park_call_exec, NULL, NULL, NULL);
05658    if (!res) {
05659       ast_manager_register_xml("ParkedCalls", 0, manager_parking_status);
05660       ast_manager_register_xml("Park", EVENT_FLAG_CALL, manager_park);
05661       ast_manager_register_xml("Bridge", EVENT_FLAG_CALL, action_bridge);
05662    }
05663 
05664    res |= ast_devstate_prov_add("Park", metermaidstate);
05665 #ifdef TEST_FRAMEWORK
05666    res |= AST_TEST_REGISTER(features_test);
05667 #endif
05668 
05669    return res;
05670 }

Generated on Sat Mar 26 11:07:37 2011 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.9