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

Generated on Wed Mar 2 18:53:26 2011 for Asterisk - the Open Source PBX by  doxygen 1.5.9