Thu Aug 30 20:43:05 2012

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 /*** MODULEINFO
00027    <support_level>core</support_level>
00028  ***/
00029 
00030 #include "asterisk.h"
00031 
00032 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 369327 $")
00033 
00034 #include "asterisk/_private.h"
00035 
00036 #include <pthread.h>
00037 #include <signal.h>
00038 #include <sys/time.h>
00039 #include <sys/signal.h>
00040 #include <netinet/in.h>
00041 
00042 #include "asterisk/lock.h"
00043 #include "asterisk/file.h"
00044 #include "asterisk/channel.h"
00045 #include "asterisk/pbx.h"
00046 #include "asterisk/causes.h"
00047 #include "asterisk/module.h"
00048 #include "asterisk/translate.h"
00049 #include "asterisk/app.h"
00050 #include "asterisk/say.h"
00051 #include "asterisk/features.h"
00052 #include "asterisk/musiconhold.h"
00053 #include "asterisk/config.h"
00054 #include "asterisk/cli.h"
00055 #include "asterisk/manager.h"
00056 #include "asterisk/utils.h"
00057 #include "asterisk/adsi.h"
00058 #include "asterisk/devicestate.h"
00059 #include "asterisk/monitor.h"
00060 #include "asterisk/audiohook.h"
00061 #include "asterisk/global_datastores.h"
00062 #include "asterisk/astobj2.h"
00063 #include "asterisk/cel.h"
00064 #include "asterisk/test.h"
00065 
00066 /*
00067  * Party A - transferee
00068  * Party B - transferer
00069  * Party C - target of transfer
00070  *
00071  * DTMF attended transfer works within the channel bridge.
00072  * Unfortunately, when either party A or B in the channel bridge
00073  * hangs up, that channel is not completely hung up until the
00074  * transfer completes.  This is a real problem depending upon
00075  * the channel technology involved.
00076  *
00077  * For chan_dahdi, the channel is crippled until the hangup is
00078  * complete.  Either the channel is not useable (analog) or the
00079  * protocol disconnect messages are held up (PRI/BRI/SS7) and
00080  * the media is not released.
00081  *
00082  * For chan_sip, a call limit of one is going to block that
00083  * endpoint from any further calls until the hangup is complete.
00084  *
00085  * For party A this is a minor problem.  The party A channel
00086  * will only be in this condition while party B is dialing and
00087  * when party B and C are conferring.  The conversation between
00088  * party B and C is expected to be a short one.  Party B is
00089  * either asking a question of party C or announcing party A.
00090  * Also party A does not have much incentive to hangup at this
00091  * point.
00092  *
00093  * For party B this can be a major problem during a blonde
00094  * transfer.  (A blonde transfer is our term for an attended
00095  * transfer that is converted into a blind transfer. :))  Party
00096  * B could be the operator.  When party B hangs up, he assumes
00097  * that he is out of the original call entirely.  The party B
00098  * channel will be in this condition while party C is ringing,
00099  * while attempting to recall party B, and while waiting between
00100  * call attempts.
00101  *
00102  * WARNING:
00103  * The ATXFER_NULL_TECH conditional is a hack to fix the
00104  * problem.  It will replace the party B channel technology with
00105  * a NULL channel driver.  The consequences of this code is that
00106  * the 'h' extension will not be able to access any channel
00107  * technology specific information like SIP statistics for the
00108  * call.
00109  *
00110  * Uncomment the ATXFER_NULL_TECH define below to replace the
00111  * party B channel technology in the channel bridge to complete
00112  * hanging up the channel technology.
00113  */
00114 //#define ATXFER_NULL_TECH 1
00115 
00116 /*** DOCUMENTATION
00117    <application name="Bridge" language="en_US">
00118       <synopsis>
00119          Bridge two channels.
00120       </synopsis>
00121       <syntax>
00122          <parameter name="channel" required="true">
00123             <para>The current channel is bridged to the specified <replaceable>channel</replaceable>.</para>
00124          </parameter>
00125          <parameter name="options">
00126             <optionlist>
00127                <option name="p">
00128                   <para>Play a courtesy tone to <replaceable>channel</replaceable>.</para>
00129                </option>
00130                <option name="h">
00131                   <para>Allow the called party to hang up by sending the
00132                   <replaceable>*</replaceable> DTMF digit.</para>
00133                </option>
00134                <option name="H">
00135                   <para>Allow the calling party to hang up by pressing the
00136                   <replaceable>*</replaceable> DTMF digit.</para>
00137                </option>
00138                <option name="k">
00139                   <para>Allow the called party to enable parking of the call by sending
00140                   the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
00141                </option>
00142                <option name="K">
00143                   <para>Allow the calling party to enable parking of the call by sending
00144                    the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
00145                </option>
00146                <option name="L(x[:y][:z])">
00147                   <para>Limit the call to <replaceable>x</replaceable> ms. Play a warning
00148                   when <replaceable>y</replaceable> ms are left. Repeat the warning every
00149                   <replaceable>z</replaceable> ms. The following special variables can be
00150                   used with this option:</para>
00151                   <variablelist>
00152                      <variable name="LIMIT_PLAYAUDIO_CALLER">
00153                         <para>Play sounds to the caller. yes|no (default yes)</para>
00154                      </variable>
00155                      <variable name="LIMIT_PLAYAUDIO_CALLEE">   
00156                         <para>Play sounds to the callee. yes|no</para>
00157                      </variable>
00158                      <variable name="LIMIT_TIMEOUT_FILE">
00159                         <para>File to play when time is up.</para>
00160                      </variable>
00161                      <variable name="LIMIT_CONNECT_FILE">
00162                         <para>File to play when call begins.</para>
00163                      </variable>
00164                      <variable name="LIMIT_WARNING_FILE">
00165                         <para>File to play as warning if <replaceable>y</replaceable> is
00166                         defined. The default is to say the time remaining.</para>
00167                      </variable>
00168                   </variablelist>
00169                </option>
00170                <option name="S(x)">
00171                   <para>Hang up the call after <replaceable>x</replaceable> seconds *after* the called party has answered the call.</para>
00172                </option>
00173                <option name="t">
00174                   <para>Allow the called party to transfer the calling party by sending the
00175                   DTMF sequence defined in <filename>features.conf</filename>.</para>
00176                </option>
00177                <option name="T">
00178                   <para>Allow the calling party to transfer the called party by sending the
00179                   DTMF sequence defined in <filename>features.conf</filename>.</para>
00180                </option>
00181                <option name="w">
00182                   <para>Allow the called party to enable recording of the call by sending
00183                   the DTMF sequence defined for one-touch recording in <filename>features.conf</filename>.</para>
00184                </option>
00185                <option name="W">
00186                   <para>Allow the calling party to enable recording of the call by sending
00187                   the DTMF sequence defined for one-touch recording in <filename>features.conf</filename>.</para>
00188                </option>
00189                <option name="x">
00190                   <para>Cause the called party to be hung up after the bridge, instead of being
00191                   restarted in the dialplan.</para>
00192                </option>
00193             </optionlist>
00194          </parameter>
00195       </syntax>
00196       <description>
00197          <para>Allows the ability to bridge two channels via the dialplan.</para>
00198          <para>This application sets the following channel variable upon completion:</para>
00199          <variablelist>
00200             <variable name="BRIDGERESULT">
00201                <para>The result of the bridge attempt as a text string.</para>
00202                <value name="SUCCESS" />
00203                <value name="FAILURE" />
00204                <value name="LOOP" />
00205                <value name="NONEXISTENT" />
00206                <value name="INCOMPATIBLE" />
00207             </variable>
00208          </variablelist>
00209       </description>
00210    </application>
00211    <application name="ParkedCall" language="en_US">
00212       <synopsis>
00213          Retrieve a parked call.
00214       </synopsis>
00215       <syntax>
00216          <parameter name="exten">
00217             <para>Parking space extension to retrieve a parked call.
00218             If not provided then the first available parked call in the
00219             parking lot will be retrieved.</para>
00220          </parameter>
00221          <parameter name="parking_lot_name">
00222             <para>Specify from which parking lot to retrieve a parked call.</para>
00223             <para>The parking lot used is selected in the following order:</para>
00224             <para>1) parking_lot_name option</para>
00225             <para>2) <variable>PARKINGLOT</variable> variable</para>
00226             <para>3) <literal>CHANNEL(parkinglot)</literal> function
00227             (Possibly preset by the channel driver.)</para>
00228             <para>4) Default parking lot.</para>
00229          </parameter>
00230       </syntax>
00231       <description>
00232          <para>Used to retrieve a parked call from a parking lot.</para>
00233          <note>
00234             <para>Parking lots automatically create and manage dialplan extensions in
00235             the parking lot context.  You do not need to explicitly use this
00236             application in your dialplan.  Instead, all you should do is include the
00237             parking lot context in your dialplan.</para>
00238          </note>
00239       </description>
00240       <see-also>
00241          <ref type="application">Park</ref>
00242          <ref type="application">ParkAndAnnounce</ref>
00243       </see-also>
00244    </application>
00245    <application name="Park" language="en_US">
00246       <synopsis>
00247          Park yourself.
00248       </synopsis>
00249       <syntax>
00250          <parameter name="timeout">
00251             <para>A custom parking timeout for this parked call. Value in milliseconds.</para>
00252          </parameter>
00253          <parameter name="return_context">
00254             <para>The context to return the call to after it times out.</para>
00255          </parameter>
00256          <parameter name="return_exten">
00257             <para>The extension to return the call to after it times out.</para>
00258          </parameter>
00259          <parameter name="return_priority">
00260             <para>The priority to return the call to after it times out.</para>
00261          </parameter>
00262          <parameter name="options">
00263             <para>A list of options for this parked call.</para>
00264             <optionlist>
00265                <option name="r">
00266                   <para>Send ringing instead of MOH to the parked call.</para>
00267                </option>
00268                <option name="R">
00269                   <para>Randomize the selection of a parking space.</para>
00270                </option>
00271                <option name="s">
00272                   <para>Silence announcement of the parking space number.</para>
00273                </option>
00274             </optionlist>
00275          </parameter>
00276          <parameter name="parking_lot_name">
00277             <para>Specify in which parking lot to park a call.</para>
00278             <para>The parking lot used is selected in the following order:</para>
00279             <para>1) parking_lot_name option</para>
00280             <para>2) <variable>PARKINGLOT</variable> variable</para>
00281             <para>3) <literal>CHANNEL(parkinglot)</literal> function
00282             (Possibly preset by the channel driver.)</para>
00283             <para>4) Default parking lot.</para>
00284          </parameter>
00285       </syntax>
00286       <description>
00287          <para>Used to park yourself (typically in combination with a supervised
00288          transfer to know the parking space).</para>
00289          <para>If you set the <variable>PARKINGEXTEN</variable> variable to a
00290          parking space extension in the parking lot, Park() will attempt to park the call
00291          on that extension.  If the extension is already is in use then execution
00292          will continue at the next priority.</para>
00293          <para>If the <literal>parkeddynamic</literal> option is enabled in <filename>features.conf</filename>
00294          the following variables can be used to dynamically create new parking lots.</para>
00295          <para>If you set the <variable>PARKINGDYNAMIC</variable> variable and this parking lot
00296          exists then it will be used as a template for the newly created dynamic lot.  Otherwise,
00297          the default parking lot will be used.</para>
00298          <para>If you set the <variable>PARKINGDYNCONTEXT</variable> variable then the newly created dynamic
00299          parking lot will use this context.</para>
00300          <para>If you set the <variable>PARKINGDYNEXTEN</variable> variable then the newly created dynamic
00301          parking lot will use this extension to access the parking lot.</para>
00302          <para>If you set the <variable>PARKINGDYNPOS</variable> variable then the newly created dynamic parking lot
00303          will use those parking postitions.</para>
00304          <note>
00305             <para>This application must be used as the first extension priority
00306             to be recognized as a parking access extension.  DTMF transfers
00307             and some channel drivers need this distinction to operate properly.
00308             The parking access extension in this case is treated like a dialplan
00309             hint.</para>
00310          </note>
00311          <note>
00312             <para>Parking lots automatically create and manage dialplan extensions in
00313             the parking lot context.  You do not need to explicitly use this
00314             application in your dialplan.  Instead, all you should do is include the
00315             parking lot context in your dialplan.</para>
00316          </note>
00317       </description>
00318       <see-also>
00319          <ref type="application">ParkAndAnnounce</ref>
00320          <ref type="application">ParkedCall</ref>
00321       </see-also>
00322    </application>
00323    <manager name="ParkedCalls" language="en_US">
00324       <synopsis>
00325          List parked calls.
00326       </synopsis>
00327       <syntax>
00328          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00329       </syntax>
00330       <description>
00331          <para>List parked calls.</para>
00332       </description>
00333    </manager>
00334    <manager name="Park" language="en_US">
00335       <synopsis>
00336          Park a channel.
00337       </synopsis>
00338       <syntax>
00339          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00340          <parameter name="Channel" required="true">
00341             <para>Channel name to park.</para>
00342          </parameter>
00343          <parameter name="Channel2" required="true">
00344             <para>Channel to return to if timeout.</para>
00345          </parameter>
00346          <parameter name="Timeout">
00347             <para>Number of milliseconds to wait before callback.</para>
00348          </parameter>
00349          <parameter name="Parkinglot">
00350             <para>Specify in which parking lot to park the channel.</para>
00351          </parameter>
00352       </syntax>
00353       <description>
00354          <para>Park a channel.</para>
00355       </description>
00356    </manager>
00357    <manager name="Bridge" language="en_US">
00358       <synopsis>
00359          Bridge two channels already in the PBX.
00360       </synopsis>
00361       <syntax>
00362          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00363          <parameter name="Channel1" required="true">
00364             <para>Channel to Bridge to Channel2.</para>
00365          </parameter>
00366          <parameter name="Channel2" required="true">
00367             <para>Channel to Bridge to Channel1.</para>
00368          </parameter>
00369          <parameter name="Tone">
00370             <para>Play courtesy tone to Channel 2.</para>
00371             <enumlist>
00372                <enum name="yes" />
00373                <enum name="no" />
00374             </enumlist>
00375          </parameter>
00376       </syntax>
00377       <description>
00378          <para>Bridge together two channels already in the PBX.</para>
00379       </description>
00380    </manager>
00381  ***/
00382 
00383 #define DEFAULT_PARK_TIME                    45000 /*!< ms */
00384 #define DEFAULT_PARK_EXTENSION                  "700"
00385 #define DEFAULT_TRANSFER_DIGIT_TIMEOUT          3000  /*!< ms */
00386 #define DEFAULT_FEATURE_DIGIT_TIMEOUT           1000  /*!< ms */
00387 #define DEFAULT_NOANSWER_TIMEOUT_ATTENDED_TRANSFER 15000 /*!< ms */
00388 #define DEFAULT_ATXFER_DROP_CALL             0     /*!< Do not drop call. */
00389 #define DEFAULT_ATXFER_LOOP_DELAY               10000 /*!< ms */
00390 #define DEFAULT_ATXFER_CALLBACK_RETRIES            2
00391 
00392 #define AST_MAX_WATCHERS 256
00393 #define MAX_DIAL_FEATURE_OPTIONS 30
00394 
00395 struct feature_group_exten {
00396    AST_LIST_ENTRY(feature_group_exten) entry;
00397    AST_DECLARE_STRING_FIELDS(
00398       AST_STRING_FIELD(exten);
00399    );
00400    struct ast_call_feature *feature;
00401 };
00402 
00403 struct feature_group {
00404    AST_LIST_ENTRY(feature_group) entry;
00405    AST_DECLARE_STRING_FIELDS(
00406       AST_STRING_FIELD(gname);
00407    );
00408    AST_LIST_HEAD_NOLOCK(, feature_group_exten) features;
00409 };
00410 
00411 static AST_RWLIST_HEAD_STATIC(feature_groups, feature_group);
00412 
00413 typedef enum {
00414    FEATURE_INTERPRET_DETECT, /* Used by ast_feature_detect */
00415    FEATURE_INTERPRET_DO,     /* Used by feature_interpret */
00416    FEATURE_INTERPRET_CHECK,  /* Used by feature_check */
00417 } feature_interpret_op;
00418 
00419 static const char *parkedcall = "ParkedCall";
00420 
00421 static char pickup_ext[AST_MAX_EXTENSION];                 /*!< Call pickup extension */
00422 
00423 /*! Parking lot access ramp dialplan usage entry. */
00424 struct parking_dp_ramp {
00425    /*! Next node in the parking lot spaces dialplan list. */
00426    AST_LIST_ENTRY(parking_dp_ramp) node;
00427    /*! TRUE if the parking lot access extension is exclusive. */
00428    unsigned int exclusive:1;
00429    /*! Parking lot access extension */
00430    char exten[1];
00431 };
00432 
00433 /*! Parking lot dialplan access ramp map */
00434 AST_LIST_HEAD_NOLOCK(parking_dp_ramp_map, parking_dp_ramp);
00435 
00436 /*! Parking lot spaces dialplan usage entry. */
00437 struct parking_dp_spaces {
00438    /*! Next node in the parking lot spaces dialplan list. */
00439    AST_LIST_ENTRY(parking_dp_spaces) node;
00440    /*! First parking space */
00441    int start;
00442    /*! Last parking space */
00443    int stop;
00444 };
00445 
00446 /*! Parking lot dialplan context space map */
00447 AST_LIST_HEAD_NOLOCK(parking_dp_space_map, parking_dp_spaces);
00448 
00449 /*! Parking lot context dialplan usage entry. */
00450 struct parking_dp_context {
00451    /*! Next node in the parking lot contexts dialplan list. */
00452    AST_LIST_ENTRY(parking_dp_context) node;
00453    /*! Parking access extensions defined in this context. */
00454    struct parking_dp_ramp_map access_extens;
00455    /*! Parking spaces defined in this context. */
00456    struct parking_dp_space_map spaces;
00457    /*! Parking hints defined in this context. */
00458    struct parking_dp_space_map hints;
00459    /*! Parking lot context name */
00460    char context[1];
00461 };
00462 
00463 /*! Parking lot dialplan usage map. */
00464 AST_LIST_HEAD_NOLOCK(parking_dp_map, parking_dp_context);
00465 
00466 /*!
00467  * \brief Description of one parked call, added to a list while active, then removed.
00468  * The list belongs to a parkinglot.
00469  */
00470 struct parkeduser {
00471    struct ast_channel *chan;                   /*!< Parked channel */
00472    struct timeval start;                       /*!< Time the park started */
00473    int parkingnum;                             /*!< Parking lot space used */
00474    char parkingexten[AST_MAX_EXTENSION];       /*!< If set beforehand, parking extension used for this call */
00475    char context[AST_MAX_CONTEXT];              /*!< Where to go if our parking time expires */
00476    char exten[AST_MAX_EXTENSION];
00477    int priority;
00478    int parkingtime;                            /*!< Maximum length in parking lot before return */
00479    /*! Method to entertain the caller when parked: AST_CONTROL_RINGING, AST_CONTROL_HOLD, or 0(none) */
00480    enum ast_control_frame_type hold_method;
00481    unsigned int notquiteyet:1;
00482    unsigned int options_specified:1;
00483    char peername[AST_CHANNEL_NAME];
00484    unsigned char moh_trys;
00485    /*! Parking lot this entry belongs to.  Holds a parking lot reference. */
00486    struct ast_parkinglot *parkinglot;
00487    AST_LIST_ENTRY(parkeduser) list;
00488 };
00489 
00490 /*! Parking lot configuration options. */
00491 struct parkinglot_cfg {
00492    /*! Music class used for parking */
00493    char mohclass[MAX_MUSICCLASS];
00494    /*! Extension to park calls in this parking lot. */
00495    char parkext[AST_MAX_EXTENSION];
00496    /*! Context for which parking is made accessible */
00497    char parking_con[AST_MAX_EXTENSION];
00498    /*! First available extension for parking */
00499    int parking_start;
00500    /*! Last available extension for parking */
00501    int parking_stop;
00502    /*! Default parking time in ms. */
00503    int parkingtime;
00504    /*!
00505     * \brief Enable DTMF based transfers on bridge when picking up parked calls.
00506     *
00507     * \details
00508     * none(0)
00509     * AST_FEATURE_FLAG_BYCALLEE
00510     * AST_FEATURE_FLAG_BYCALLER
00511     * AST_FEATURE_FLAG_BYBOTH
00512     */
00513    int parkedcalltransfers;
00514    /*!
00515     * \brief Enable DTMF based parking on bridge when picking up parked calls.
00516     *
00517     * \details
00518     * none(0)
00519     * AST_FEATURE_FLAG_BYCALLEE
00520     * AST_FEATURE_FLAG_BYCALLER
00521     * AST_FEATURE_FLAG_BYBOTH
00522     */
00523    int parkedcallreparking;
00524    /*!
00525     * \brief Enable DTMF based hangup on a bridge when pickup up parked calls.
00526     *
00527     * \details
00528     * none(0)
00529     * AST_FEATURE_FLAG_BYCALLEE
00530     * AST_FEATURE_FLAG_BYCALLER
00531     * AST_FEATURE_FLAG_BYBOTH
00532     */
00533    int parkedcallhangup;
00534    /*!
00535     * \brief Enable DTMF based recording on a bridge when picking up parked calls.
00536     *
00537     * \details
00538     * none(0)
00539     * AST_FEATURE_FLAG_BYCALLEE
00540     * AST_FEATURE_FLAG_BYCALLER
00541     * AST_FEATURE_FLAG_BYBOTH
00542     */
00543    int parkedcallrecording;
00544 
00545    /*! TRUE if findslot is set to next */
00546    unsigned int parkfindnext:1;
00547    /*! TRUE if the parking lot is exclusively accessed by parkext */
00548    unsigned int parkext_exclusive:1;
00549    /*! Add parking hints automatically */
00550    unsigned int parkaddhints:1;
00551    /*! TRUE if configuration is invalid and the parking lot should not be used. */
00552    unsigned int is_invalid:1;
00553 };
00554 
00555 /*! \brief Structure for parking lots which are put in a container. */
00556 struct ast_parkinglot {
00557    /*! Name of the parking lot. */
00558    char name[AST_MAX_CONTEXT];
00559    /*! Parking lot user configuration. */
00560    struct parkinglot_cfg cfg;
00561 
00562    /*! Parking space to start next park search. */
00563    int next_parking_space;
00564 
00565    /*! That which bears the_mark shall be deleted if parking lot empty! (Used during reloads.) */
00566    unsigned int the_mark:1;
00567    /*! TRUE if the parking lot is disabled. */
00568    unsigned int disabled:1;
00569 
00570    /*! List of active parkings in this parkinglot */
00571    AST_LIST_HEAD(parkinglot_parklist, parkeduser) parkings;
00572 };
00573 
00574 /*! \brief The configured parking lots container. Always at least one  - the default parking lot */
00575 static struct ao2_container *parkinglots;
00576 
00577 /*!
00578  * \brief Default parking lot.
00579  * \note Holds a parkinglot reference.
00580  * \note Will not be NULL while running.
00581  */
00582 static struct ast_parkinglot *default_parkinglot;
00583 
00584 /*! Force a config reload to reload regardless of config file timestamp. */
00585 static int force_reload_load;
00586 
00587 static int parkedplay = 0;                                 /*!< Who to play courtesytone to when someone picks up a parked call. */
00588 static int parkeddynamic = 0;                              /*!< Enable creation of parkinglots dynamically */
00589 static char courtesytone[256];                             /*!< Courtesy tone used to pickup parked calls and on-touch-record */
00590 static char xfersound[256];                                /*!< Call transfer sound */
00591 static char xferfailsound[256];                            /*!< Call transfer failure sound */
00592 static char pickupsound[256];                              /*!< Pickup sound */
00593 static char pickupfailsound[256];                          /*!< Pickup failure sound */
00594 
00595 /*!
00596  * \brief Context for parking dialback to parker.
00597  * \note The need for the context is a KLUDGE.
00598  *
00599  * \todo Might be able to eliminate the parking_con_dial context
00600  * kludge by running app_dial directly in its own thread to
00601  * simulate a PBX.
00602  */
00603 static char parking_con_dial[] = "park-dial";
00604 
00605 /*! Ensure that features.conf reloads on one thread at a time. */
00606 AST_MUTEX_DEFINE_STATIC(features_reload_lock);
00607 
00608 static int adsipark;
00609 
00610 static int transferdigittimeout;
00611 static int featuredigittimeout;
00612 static int comebacktoorigin = 1;
00613 
00614 static int atxfernoanswertimeout;
00615 static unsigned int atxferdropcall;
00616 static unsigned int atxferloopdelay;
00617 static unsigned int atxfercallbackretries;
00618 
00619 static char *registrar = "features";         /*!< Registrar for operations */
00620 
00621 /*! PARK_APP_NAME application arguments */
00622 AST_DEFINE_APP_ARGS_TYPE(park_app_args,
00623    AST_APP_ARG(timeout);      /*!< Time in ms to remain in the parking lot. */
00624    AST_APP_ARG(return_con);   /*!< Context to return parked call if timeout. */
00625    AST_APP_ARG(return_ext);   /*!< Exten to return parked call if timeout. */
00626    AST_APP_ARG(return_pri);   /*!< Priority to return parked call if timeout. */
00627    AST_APP_ARG(options);      /*!< Parking option flags. */
00628    AST_APP_ARG(pl_name);      /*!< Parking lot name to use if present. */
00629    AST_APP_ARG(dummy);        /*!< Place to put any remaining args string. */
00630    );
00631 
00632 /* module and CLI command definitions */
00633 static const char *parkcall = "Park";
00634 
00635 static struct ast_app *monitor_app = NULL;
00636 static int monitor_ok = 1;
00637 
00638 static struct ast_app *mixmonitor_app = NULL;
00639 static int mixmonitor_ok = 1;
00640 
00641 static struct ast_app *stopmixmonitor_app = NULL;
00642 static int stopmixmonitor_ok = 1;
00643 
00644 static pthread_t parking_thread;
00645 struct ast_dial_features {
00646    /*! Channel's feature flags. */
00647    struct ast_flags my_features;
00648    /*! Bridge peer's feature flags. */
00649    struct ast_flags peer_features;
00650 };
00651 
00652 #if defined(ATXFER_NULL_TECH)
00653 /*!
00654  * \internal
00655  * \brief Set the channel technology to the kill technology.
00656  *
00657  * \param chan Channel to change technology.
00658  *
00659  * \return Nothing
00660  */
00661 static void set_kill_chan_tech(struct ast_channel *chan)
00662 {
00663    int idx;
00664 
00665    ast_channel_lock(chan);
00666 
00667    /* Hangup the channel's physical side */
00668    if (chan->tech->hangup) {
00669       chan->tech->hangup(chan);
00670    }
00671    if (chan->tech_pvt) {
00672       ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n",
00673          chan->name);
00674       ast_free(chan->tech_pvt);
00675       chan->tech_pvt = NULL;
00676    }
00677 
00678    /* Install the kill technology and wake up anyone waiting on it. */
00679    chan->tech = &ast_kill_tech;
00680    for (idx = 0; idx < AST_MAX_FDS; ++idx) {
00681       switch (idx) {
00682       case AST_ALERT_FD:
00683       case AST_TIMING_FD:
00684       case AST_GENERATOR_FD:
00685          /* Don't clear these fd's. */
00686          break;
00687       default:
00688          ast_channel_set_fd(chan, idx, -1);
00689          break;
00690       }
00691    }
00692    ast_queue_frame(chan, &ast_null_frame);
00693 
00694    ast_channel_unlock(chan);
00695 }
00696 #endif   /* defined(ATXFER_NULL_TECH) */
00697 
00698 #if defined(ATXFER_NULL_TECH)
00699 /*!
00700  * \internal
00701  * \brief Set the channel name to something unique.
00702  *
00703  * \param chan Channel to change name.
00704  *
00705  * \return Nothing
00706  */
00707 static void set_new_chan_name(struct ast_channel *chan)
00708 {
00709    static int seq_num_last;
00710    int seq_num;
00711    int len;
00712    char *chan_name;
00713    char dummy[1];
00714 
00715    /* Create the new channel name string. */
00716    ast_channel_lock(chan);
00717    seq_num = ast_atomic_fetchadd_int(&seq_num_last, +1);
00718    len = snprintf(dummy, sizeof(dummy), "%s<XFER_%x>", chan->name, seq_num) + 1;
00719    chan_name = alloca(len);
00720    snprintf(chan_name, len, "%s<XFER_%x>", chan->name, seq_num);
00721    ast_channel_unlock(chan);
00722 
00723    ast_change_name(chan, chan_name);
00724 }
00725 #endif   /* defined(ATXFER_NULL_TECH) */
00726 
00727 static void *dial_features_duplicate(void *data)
00728 {
00729    struct ast_dial_features *df = data, *df_copy;
00730  
00731    if (!(df_copy = ast_calloc(1, sizeof(*df)))) {
00732       return NULL;
00733    }
00734  
00735    memcpy(df_copy, df, sizeof(*df));
00736  
00737    return df_copy;
00738 }
00739 
00740 static void dial_features_destroy(void *data)
00741 {
00742    struct ast_dial_features *df = data;
00743    if (df) {
00744       ast_free(df);
00745    }
00746 }
00747 
00748 static const struct ast_datastore_info dial_features_info = {
00749    .type = "dial-features",
00750    .destroy = dial_features_destroy,
00751    .duplicate = dial_features_duplicate,
00752 };
00753 
00754 /*!
00755  * \internal
00756  * \brief Set the features datastore if it doesn't exist.
00757  *
00758  * \param chan Channel to add features datastore
00759  * \param my_features The channel's feature flags
00760  * \param peer_features The channel's bridge peer feature flags
00761  *
00762  * \retval TRUE if features datastore already existed.
00763  */
00764 static int add_features_datastore(struct ast_channel *chan, const struct ast_flags *my_features, const struct ast_flags *peer_features)
00765 {
00766    struct ast_datastore *datastore;
00767    struct ast_dial_features *dialfeatures;
00768 
00769    ast_channel_lock(chan);
00770    datastore = ast_channel_datastore_find(chan, &dial_features_info, NULL);
00771    ast_channel_unlock(chan);
00772    if (datastore) {
00773       /* Already exists. */
00774       return 1;
00775    }
00776 
00777    /* Create a new datastore with specified feature flags. */
00778    datastore = ast_datastore_alloc(&dial_features_info, NULL);
00779    if (!datastore) {
00780       ast_log(LOG_WARNING, "Unable to create channel features datastore.\n");
00781       return 0;
00782    }
00783    dialfeatures = ast_calloc(1, sizeof(*dialfeatures));
00784    if (!dialfeatures) {
00785       ast_log(LOG_WARNING, "Unable to allocate memory for feature flags.\n");
00786       ast_datastore_free(datastore);
00787       return 0;
00788    }
00789    ast_copy_flags(&dialfeatures->my_features, my_features, AST_FLAGS_ALL);
00790    ast_copy_flags(&dialfeatures->peer_features, peer_features, AST_FLAGS_ALL);
00791    datastore->inheritance = DATASTORE_INHERIT_FOREVER;
00792    datastore->data = dialfeatures;
00793    ast_channel_lock(chan);
00794    ast_channel_datastore_add(chan, datastore);
00795    ast_channel_unlock(chan);
00796    return 0;
00797 }
00798 
00799 /* Forward declarations */
00800 static struct ast_parkinglot *parkinglot_addref(struct ast_parkinglot *parkinglot);
00801 static void parkinglot_unref(struct ast_parkinglot *parkinglot);
00802 static struct ast_parkinglot *find_parkinglot(const char *name);
00803 static struct ast_parkinglot *create_parkinglot(const char *name);
00804 static struct ast_parkinglot *copy_parkinglot(const char *name, const struct ast_parkinglot *parkinglot);
00805 static int parkinglot_activate(struct ast_parkinglot *parkinglot);
00806 static int play_message_on_chan(struct ast_channel *play_to, struct ast_channel *other, const char *msg, const char *audiofile);
00807 
00808 /*!
00809  * \internal
00810  * \brief Get the parking extension if it exists.
00811  *
00812  * \param exten_str Parking extension to see if exists.
00813  * \param chan Channel to autoservice while looking for exten.  (Could be NULL)
00814  * \param context Parking context to look in for exten.
00815  *
00816  * \retval exten on success.
00817  * \retval NULL on error or exten does not exist.
00818  */
00819 static struct ast_exten *get_parking_exten(const char *exten_str, struct ast_channel *chan, const char *context)
00820 {
00821    struct ast_exten *exten;
00822    struct pbx_find_info q = { .stacklen = 0 }; /* the rest is reset in pbx_find_extension */
00823    const char *app_at_exten;
00824 
00825    ast_debug(4, "Checking if %s@%s is a parking exten\n", exten_str, context);
00826    exten = pbx_find_extension(chan, NULL, &q, context, exten_str, 1, NULL, NULL,
00827       E_MATCH);
00828    if (!exten) {
00829       return NULL;
00830    }
00831 
00832    app_at_exten = ast_get_extension_app(exten);
00833    if (!app_at_exten || strcasecmp(parkcall, app_at_exten)) {
00834       return NULL;
00835    }
00836 
00837    return exten;
00838 }
00839 
00840 int ast_parking_ext_valid(const char *exten_str, struct ast_channel *chan, const char *context)
00841 {
00842    return get_parking_exten(exten_str, chan, context) ? 1 : 0;
00843 }
00844 
00845 const char *ast_pickup_ext(void)
00846 {
00847    return pickup_ext;
00848 }
00849 
00850 struct ast_bridge_thread_obj 
00851 {
00852    struct ast_bridge_config bconfig;
00853    struct ast_channel *chan;
00854    struct ast_channel *peer;
00855    unsigned int return_to_pbx:1;
00856 };
00857 
00858 static int parkinglot_hash_cb(const void *obj, const int flags)
00859 {
00860    const struct ast_parkinglot *parkinglot = obj;
00861 
00862    return ast_str_case_hash(parkinglot->name);
00863 }
00864 
00865 static int parkinglot_cmp_cb(void *obj, void *arg, int flags)
00866 {
00867    struct ast_parkinglot *parkinglot = obj;
00868    struct ast_parkinglot *parkinglot2 = arg;
00869 
00870    return !strcasecmp(parkinglot->name, parkinglot2->name) ? CMP_MATCH | CMP_STOP : 0;
00871 }
00872 
00873 /*!
00874  * \brief store context, extension and priority 
00875  * \param chan, context, ext, pri
00876  */
00877 static void set_c_e_p(struct ast_channel *chan, const char *context, const char *ext, int pri)
00878 {
00879    ast_copy_string(chan->context, context, sizeof(chan->context));
00880    ast_copy_string(chan->exten, ext, sizeof(chan->exten));
00881    chan->priority = pri;
00882 }
00883 
00884 /*!
00885  * \brief Check goto on transfer
00886  * \param chan
00887  *
00888  * Check if channel has 'GOTO_ON_BLINDXFR' set, if not exit.
00889  * When found make sure the types are compatible. Check if channel is valid
00890  * if so start the new channel else hangup the call. 
00891  */
00892 static void check_goto_on_transfer(struct ast_channel *chan) 
00893 {
00894    struct ast_channel *xferchan;
00895    const char *val;
00896    char *goto_on_transfer;
00897    char *x;
00898 
00899    ast_channel_lock(chan);
00900    val = pbx_builtin_getvar_helper(chan, "GOTO_ON_BLINDXFR");
00901    if (ast_strlen_zero(val)) {
00902       ast_channel_unlock(chan);
00903       return;
00904    }
00905    goto_on_transfer = ast_strdupa(val);
00906    ast_channel_unlock(chan);
00907 
00908    ast_debug(1, "Attempting GOTO_ON_BLINDXFR=%s for %s.\n", val, chan->name);
00909 
00910    xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", chan->linkedid, 0,
00911       "%s", chan->name);
00912    if (!xferchan) {
00913       return;
00914    }
00915 
00916    /* Make formats okay */
00917    xferchan->readformat = chan->readformat;
00918    xferchan->writeformat = chan->writeformat;
00919 
00920    if (ast_channel_masquerade(xferchan, chan)) {
00921       /* Failed to setup masquerade. */
00922       ast_hangup(xferchan);
00923       return;
00924    }
00925 
00926    for (x = goto_on_transfer; *x; ++x) {
00927       if (*x == '^') {
00928          *x = ',';
00929       }
00930    }
00931    ast_parseable_goto(xferchan, goto_on_transfer);
00932    xferchan->_state = AST_STATE_UP;
00933    ast_clear_flag(xferchan, AST_FLAGS_ALL);  
00934    ast_channel_clear_softhangup(xferchan, AST_SOFTHANGUP_ALL);
00935 
00936    ast_do_masquerade(xferchan);
00937    if (ast_pbx_start(xferchan)) {
00938       /* Failed to start PBX. */
00939       ast_hangup(xferchan);
00940    }
00941 }
00942 
00943 static struct ast_channel *feature_request_and_dial(struct ast_channel *caller,
00944    const char *caller_name, struct ast_channel *requestor,
00945    struct ast_channel *transferee, const char *type, format_t format, void *data,
00946    int timeout, int *outstate, const char *language);
00947 
00948 /*!
00949  * \brief bridge the call 
00950  * \param data thread bridge.
00951  *
00952  * Set Last Data for respective channels, reset cdr for channels
00953  * bridge call, check if we're going back to dialplan
00954  * if not hangup both legs of the call
00955  */
00956 static void *bridge_call_thread(void *data)
00957 {
00958    struct ast_bridge_thread_obj *tobj = data;
00959 
00960    tobj->chan->appl = !tobj->return_to_pbx ? "Transferred Call" : "ManagerBridge";
00961    tobj->chan->data = tobj->peer->name;
00962    tobj->peer->appl = !tobj->return_to_pbx ? "Transferred Call" : "ManagerBridge";
00963    tobj->peer->data = tobj->chan->name;
00964 
00965    ast_bridge_call(tobj->peer, tobj->chan, &tobj->bconfig);
00966 
00967    if (tobj->return_to_pbx) {
00968       if (!ast_check_hangup(tobj->peer)) {
00969          ast_log(LOG_VERBOSE, "putting peer %s into PBX again\n", tobj->peer->name);
00970          if (ast_pbx_start(tobj->peer)) {
00971             ast_log(LOG_WARNING, "FAILED continuing PBX on peer %s\n", tobj->peer->name);
00972             ast_hangup(tobj->peer);
00973          }
00974       } else {
00975          ast_hangup(tobj->peer);
00976       }
00977       if (!ast_check_hangup(tobj->chan)) {
00978          ast_log(LOG_VERBOSE, "putting chan %s into PBX again\n", tobj->chan->name);
00979          if (ast_pbx_start(tobj->chan)) {
00980             ast_log(LOG_WARNING, "FAILED continuing PBX on chan %s\n", tobj->chan->name);
00981             ast_hangup(tobj->chan);
00982          }
00983       } else {
00984          ast_hangup(tobj->chan);
00985       }
00986    } else {
00987       ast_hangup(tobj->chan);
00988       ast_hangup(tobj->peer);
00989    }
00990 
00991    ast_free(tobj);
00992 
00993    return NULL;
00994 }
00995 
00996 /*!
00997  * \brief create thread for the parked call
00998  * \param data
00999  *
01000  * Create thread and attributes, call bridge_call_thread
01001  */
01002 static void bridge_call_thread_launch(struct ast_bridge_thread_obj *data)
01003 {
01004    pthread_t thread;
01005    pthread_attr_t attr;
01006    struct sched_param sched;
01007 
01008    pthread_attr_init(&attr);
01009    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
01010    if (ast_pthread_create(&thread, &attr, bridge_call_thread, data)) {
01011       ast_hangup(data->chan);
01012       ast_hangup(data->peer);
01013       ast_log(LOG_ERROR, "Failed to create bridge_call_thread.\n");
01014    }
01015    pthread_attr_destroy(&attr);
01016    memset(&sched, 0, sizeof(sched));
01017    pthread_setschedparam(thread, SCHED_RR, &sched);
01018 }
01019 
01020 /*!
01021  * \brief Announce call parking by ADSI
01022  * \param chan .
01023  * \param parkingexten .
01024  * Create message to show for ADSI, display message.
01025  * \retval 0 on success.
01026  * \retval -1 on failure.
01027  */
01028 static int adsi_announce_park(struct ast_channel *chan, char *parkingexten)
01029 {
01030    int res;
01031    int justify[5] = {ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT};
01032    char tmp[256];
01033    char *message[5] = {NULL, NULL, NULL, NULL, NULL};
01034 
01035    snprintf(tmp, sizeof(tmp), "Parked on %s", parkingexten);
01036    message[0] = tmp;
01037    res = ast_adsi_load_session(chan, NULL, 0, 1);
01038    if (res == -1)
01039       return res;
01040    return ast_adsi_print(chan, message, justify, 1);
01041 }
01042 
01043 /*!
01044  * \brief Find parking lot name from channel
01045  * \note Channel needs to be locked while the returned string is in use.
01046  */
01047 static const char *findparkinglotname(struct ast_channel *chan)
01048 {
01049    const char *name;
01050 
01051    /* The channel variable overrides everything */
01052    name = pbx_builtin_getvar_helper(chan, "PARKINGLOT");
01053    if (!name && !ast_strlen_zero(chan->parkinglot)) {
01054       /* Use the channel's parking lot. */
01055       name = chan->parkinglot;
01056    }
01057    return name;
01058 }
01059 
01060 /*! \brief Notify metermaids that we've changed an extension */
01061 static void notify_metermaids(const char *exten, char *context, enum ast_device_state state)
01062 {
01063    ast_debug(4, "Notification of state change to metermaids %s@%s\n to state '%s'", 
01064       exten, context, ast_devstate2str(state));
01065 
01066    ast_devstate_changed(state, "park:%s@%s", exten, context);
01067 }
01068 
01069 /*! \brief metermaids callback from devicestate.c */
01070 static enum ast_device_state metermaidstate(const char *data)
01071 {
01072    char *context;
01073    char *exten;
01074 
01075    context = ast_strdupa(data);
01076 
01077    exten = strsep(&context, "@");
01078    if (!context)
01079       return AST_DEVICE_INVALID;
01080    
01081    ast_debug(4, "Checking state of exten %s in context %s\n", exten, context);
01082 
01083    if (!ast_exists_extension(NULL, context, exten, 1, NULL))
01084       return AST_DEVICE_NOT_INUSE;
01085 
01086    return AST_DEVICE_INUSE;
01087 }
01088 
01089 /*! Options to pass to park_call_full */
01090 enum ast_park_call_options {
01091    /*! Provide ringing to the parked caller instead of music on hold */
01092    AST_PARK_OPT_RINGING =   (1 << 0),
01093    /*! Randomly choose a parking spot for the caller instead of choosing
01094     *  the first one that is available. */
01095    AST_PARK_OPT_RANDOMIZE = (1 << 1),
01096    /*! Do not announce the parking number */
01097    AST_PARK_OPT_SILENCE = (1 << 2),
01098 };
01099 
01100 /*! Optional additional parking options when parking a call. */
01101 struct ast_park_call_args {
01102    /*! How long to wait in the parking lot before the call gets sent back
01103     *  to the specified return extension (or a best guess at where it came
01104     *  from if not explicitly specified). */
01105    int timeout;
01106    /*! An output parameter to store the parking space where the parked caller
01107     *  was placed. */
01108    int *extout;
01109    const char *orig_chan_name;
01110    const char *return_con;
01111    const char *return_ext;
01112    int return_pri;
01113    uint32_t flags;
01114    /*! Parked user that has already obtained a parking space */
01115    struct parkeduser *pu;
01116    /*! \brief Parkinglot to be parked in */
01117    struct ast_parkinglot *parkinglot;
01118 };
01119 
01120 /*!
01121  * \internal
01122  * \brief Create a dynamic parking lot.
01123  *
01124  * \param name Dynamic parking lot name to create.
01125  * \param chan Channel to get dynamic parking lot parameters.
01126  *
01127  * \retval parkinglot on success.
01128  * \retval NULL on error.
01129  */
01130 static struct ast_parkinglot *create_dynamic_parkinglot(const char *name, struct ast_channel *chan)
01131 {
01132    const char *dyn_context;
01133    const char *dyn_exten;
01134    const char *dyn_range;
01135    const char *template_name;
01136    struct ast_parkinglot *template_parkinglot = NULL;
01137    struct ast_parkinglot *parkinglot;
01138    int dyn_start;
01139    int dyn_end;
01140 
01141    ast_channel_lock(chan);
01142    template_name = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNAMIC"), ""));
01143    dyn_context = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNCONTEXT"), ""));
01144    dyn_exten = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNEXTEN"), ""));
01145    dyn_range = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNPOS"), ""));
01146    ast_channel_unlock(chan);
01147 
01148    if (!ast_strlen_zero(template_name)) {
01149       template_parkinglot = find_parkinglot(template_name);
01150       if (!template_parkinglot) {
01151          ast_debug(1, "PARKINGDYNAMIC lot %s does not exist.\n",
01152             template_name);
01153       } else if (template_parkinglot->cfg.is_invalid) {
01154          ast_debug(1, "PARKINGDYNAMIC lot %s has invalid config.\n",
01155             template_name);
01156          parkinglot_unref(template_parkinglot);
01157          template_parkinglot = NULL;
01158       }
01159    }
01160    if (!template_parkinglot) {
01161       template_parkinglot = parkinglot_addref(default_parkinglot);
01162       ast_debug(1, "Using default parking lot for template\n");
01163    }
01164 
01165    parkinglot = copy_parkinglot(name, template_parkinglot);
01166    if (!parkinglot) {
01167       ast_log(LOG_ERROR, "Could not build dynamic parking lot!\n");
01168    } else {
01169       /* Configure the dynamic parking lot. */
01170       if (!ast_strlen_zero(dyn_context)) {
01171          ast_copy_string(parkinglot->cfg.parking_con, dyn_context,
01172             sizeof(parkinglot->cfg.parking_con));
01173       }
01174       if (!ast_strlen_zero(dyn_exten)) {
01175          ast_copy_string(parkinglot->cfg.parkext, dyn_exten,
01176             sizeof(parkinglot->cfg.parkext));
01177       }
01178       if (!ast_strlen_zero(dyn_range)) {
01179          if (sscanf(dyn_range, "%30d-%30d", &dyn_start, &dyn_end) != 2) {
01180             ast_log(LOG_WARNING,
01181                "Format for parking positions is a-b, where a and b are numbers\n");
01182          } else if (dyn_end < dyn_start || dyn_start <= 0 || dyn_end <= 0) {
01183             ast_log(LOG_WARNING,
01184                "Format for parking positions is a-b, where a <= b\n");
01185          } else {
01186             parkinglot->cfg.parking_start = dyn_start;
01187             parkinglot->cfg.parking_stop = dyn_end;
01188          }
01189       }
01190 
01191       /*
01192        * Sanity check for dynamic parking lot configuration.
01193        *
01194        * XXX It may be desirable to instead check if the dynamic
01195        * parking lot overlaps any existing lots like what is done for
01196        * a reload.
01197        */
01198       if (!strcmp(parkinglot->cfg.parking_con, template_parkinglot->cfg.parking_con)) {
01199          if (!strcmp(parkinglot->cfg.parkext, template_parkinglot->cfg.parkext)
01200             && parkinglot->cfg.parkext_exclusive) {
01201             ast_log(LOG_WARNING,
01202                "Parking lot '%s' conflicts with template parking lot '%s'!\n"
01203                "Change either PARKINGDYNCONTEXT or PARKINGDYNEXTEN.\n",
01204                parkinglot->name, template_parkinglot->name);
01205          }
01206          if ((template_parkinglot->cfg.parking_start <= parkinglot->cfg.parking_start
01207                && parkinglot->cfg.parking_start <= template_parkinglot->cfg.parking_stop)
01208             || (template_parkinglot->cfg.parking_start <= parkinglot->cfg.parking_stop
01209                && parkinglot->cfg.parking_stop <= template_parkinglot->cfg.parking_stop)
01210             || (parkinglot->cfg.parking_start < template_parkinglot->cfg.parking_start
01211                && template_parkinglot->cfg.parking_stop < parkinglot->cfg.parking_stop)) {
01212             ast_log(LOG_WARNING,
01213                "Parking lot '%s' parking spaces overlap template parking lot '%s'!\n"
01214                "Change PARKINGDYNPOS.\n",
01215                parkinglot->name, template_parkinglot->name);
01216          }
01217       }
01218 
01219       parkinglot_activate(parkinglot);
01220       ao2_link(parkinglots, parkinglot);
01221    }
01222    parkinglot_unref(template_parkinglot);
01223 
01224    return parkinglot;
01225 }
01226 
01227 /*!
01228  * \internal
01229  * \brief Abort parking a call that has not completed parking yet.
01230  *
01231  * \param pu Parked user item to clean up.
01232  *
01233  * \note The parking lot parkings list is locked on entry.
01234  *
01235  * \return Nothing
01236  */
01237 static void park_space_abort(struct parkeduser *pu)
01238 {
01239    struct ast_parkinglot *parkinglot;
01240 
01241    parkinglot = pu->parkinglot;
01242 
01243    /* Put back the parking space just allocated. */
01244    --parkinglot->next_parking_space;
01245 
01246    AST_LIST_REMOVE(&parkinglot->parkings, pu, list);
01247 
01248    AST_LIST_UNLOCK(&parkinglot->parkings);
01249    parkinglot_unref(parkinglot);
01250    ast_free(pu);
01251 }
01252 
01253 /*!
01254  * \internal
01255  * \brief Reserve a parking space in a parking lot for a call being parked.
01256  *
01257  * \param park_me Channel being parked.
01258  * \param parker Channel parking the call.
01259  * \param args Optional additional parking options when parking a call.
01260  *
01261  * \return Parked call descriptor or NULL if failed.
01262  * \note The parking lot list is locked if successful.
01263  */
01264 static struct parkeduser *park_space_reserve(struct ast_channel *park_me, struct ast_channel *parker, struct ast_park_call_args *args)
01265 {
01266    struct parkeduser *pu;
01267    int i;
01268    int parking_space = -1;
01269    const char *parkinglotname;
01270    const char *parkingexten;
01271    struct parkeduser *cur;
01272    struct ast_parkinglot *parkinglot = NULL;
01273 
01274    if (args->parkinglot) {
01275       parkinglot = parkinglot_addref(args->parkinglot);
01276       parkinglotname = parkinglot->name;
01277    } else {
01278       if (parker) {
01279          parkinglotname = findparkinglotname(parker);
01280       } else { /* parker was NULL, check park_me (ParkAndAnnounce / res_agi) */
01281          parkinglotname = findparkinglotname(park_me);
01282       }
01283       if (!ast_strlen_zero(parkinglotname)) {
01284          parkinglot = find_parkinglot(parkinglotname);
01285       } else {
01286          /* Parking lot is not specified, so use the default parking lot. */
01287          ast_debug(4, "This could be an indication channel driver needs updating, using default lot.\n");
01288          parkinglot = parkinglot_addref(default_parkinglot);
01289       }
01290    }
01291 
01292    /* Dynamically create parkinglot */
01293    if (!parkinglot && parkeddynamic && !ast_strlen_zero(parkinglotname)) {
01294       parkinglot = create_dynamic_parkinglot(parkinglotname, park_me);
01295    }
01296 
01297    if (!parkinglot) {
01298       ast_log(LOG_WARNING, "Parking lot not available to park %s.\n", park_me->name);
01299       return NULL;
01300    }
01301 
01302    ast_debug(1, "Parking lot: %s\n", parkinglot->name);
01303    if (parkinglot->disabled || parkinglot->cfg.is_invalid) {
01304       ast_log(LOG_WARNING, "Parking lot %s is not in a useable state.\n",
01305          parkinglot->name);
01306       parkinglot_unref(parkinglot);
01307       return NULL;
01308    }
01309 
01310    /* Allocate memory for parking data */
01311    if (!(pu = ast_calloc(1, sizeof(*pu)))) {
01312       parkinglot_unref(parkinglot);
01313       return NULL;
01314    }
01315 
01316    /* Lock parking list */
01317    AST_LIST_LOCK(&parkinglot->parkings);
01318 
01319    /* Check for channel variable PARKINGEXTEN */
01320    parkingexten = ast_strdupa(S_OR(pbx_builtin_getvar_helper(park_me, "PARKINGEXTEN"), ""));
01321    if (!ast_strlen_zero(parkingexten)) {
01322       /*!
01323        * \note The API forces us to specify a numeric parking slot, even
01324        * though the architecture would tend to support non-numeric extensions
01325        * (as are possible with SIP, for example).  Hence, we enforce that
01326        * limitation here.  If extout was not numeric, we could permit
01327        * arbitrary non-numeric extensions.
01328        */
01329       if (sscanf(parkingexten, "%30d", &parking_space) != 1 || parking_space <= 0) {
01330          ast_log(LOG_WARNING, "PARKINGEXTEN='%s' is not a valid parking space.\n",
01331             parkingexten);
01332          AST_LIST_UNLOCK(&parkinglot->parkings);
01333          parkinglot_unref(parkinglot);
01334          ast_free(pu);
01335          return NULL;
01336       }
01337 
01338       if (parking_space < parkinglot->cfg.parking_start
01339          || parkinglot->cfg.parking_stop < parking_space) {
01340          /*
01341           * Cannot allow park because parking lots are not setup for
01342           * spaces outside of the lot.  (Things like dialplan hints don't
01343           * exist for outside lot space.)
01344           */
01345          ast_log(LOG_WARNING, "PARKINGEXTEN=%d is not in %s (%d-%d).\n",
01346             parking_space, parkinglot->name, parkinglot->cfg.parking_start,
01347             parkinglot->cfg.parking_stop);
01348          AST_LIST_UNLOCK(&parkinglot->parkings);
01349          parkinglot_unref(parkinglot);
01350          ast_free(pu);
01351          return NULL;
01352       }
01353 
01354       /* Check if requested parking space is in use. */
01355       AST_LIST_TRAVERSE(&parkinglot->parkings, cur, list) {
01356          if (cur->parkingnum == parking_space) {
01357             ast_log(LOG_WARNING, "PARKINGEXTEN=%d is already in use in %s\n",
01358                parking_space, parkinglot->name);
01359             AST_LIST_UNLOCK(&parkinglot->parkings);
01360             parkinglot_unref(parkinglot);
01361             ast_free(pu);
01362             return NULL;
01363          }
01364       }
01365    } else {
01366       /* PARKINGEXTEN is empty, so find a usable extension in the lot to park the call */
01367       int start; /* The first slot we look in the parkinglot. It can be randomized. */
01368       int start_checked = 0; /* flag raised once the first slot is checked */
01369 
01370       /* If using randomize mode, set start to random position on parking range */
01371       if (ast_test_flag(args, AST_PARK_OPT_RANDOMIZE)) {
01372          start = ast_random() % (parkinglot->cfg.parking_stop - parkinglot->cfg.parking_start + 1);
01373          start += parkinglot->cfg.parking_start;
01374       } else if (parkinglot->cfg.parkfindnext
01375          && parkinglot->cfg.parking_start <= parkinglot->next_parking_space
01376          && parkinglot->next_parking_space <= parkinglot->cfg.parking_stop) {
01377          /* Start looking with the next parking space in the lot. */
01378          start = parkinglot->next_parking_space;
01379       } else {
01380          /* Otherwise, just set it to the start position. */
01381          start = parkinglot->cfg.parking_start;
01382       }
01383 
01384       /* free parking extension linear search: O(n^2) */
01385       for (i = start; ; i++) {
01386          /* If we are past the end, wrap around to the first parking slot*/
01387          if (i == parkinglot->cfg.parking_stop + 1) {
01388             i = parkinglot->cfg.parking_start;
01389          }
01390 
01391          if (i == start) {
01392             /* At this point, if start_checked, we've exhausted all the possible slots. */
01393             if (start_checked) {
01394                break;
01395             } else {
01396                start_checked = 1;
01397             }
01398          }
01399 
01400          /* Search the list of parked calls already in use for i. If we find it, it's in use. */
01401          AST_LIST_TRAVERSE(&parkinglot->parkings, cur, list) {
01402             if (cur->parkingnum == i) {
01403                break;
01404             }
01405          }
01406          if (!cur) {
01407             /* We found a parking space. */
01408             parking_space = i;
01409             break;
01410          }
01411       }
01412       if (parking_space == -1) {
01413          /* We did not find a parking space.  Lot is full. */
01414          ast_log(LOG_WARNING, "No more parking spaces in %s\n", parkinglot->name);
01415          AST_LIST_UNLOCK(&parkinglot->parkings);
01416          parkinglot_unref(parkinglot);
01417          ast_free(pu);
01418          return NULL;
01419       }
01420    }
01421 
01422    /* Prepare for next parking space search. */
01423    parkinglot->next_parking_space = parking_space + 1;
01424 
01425    snprintf(pu->parkingexten, sizeof(pu->parkingexten), "%d", parking_space);
01426    pu->notquiteyet = 1;
01427    pu->parkingnum = parking_space;
01428    pu->parkinglot = parkinglot;
01429    AST_LIST_INSERT_TAIL(&parkinglot->parkings, pu, list);
01430 
01431    return pu;
01432 }
01433 
01434 /* Park a call */
01435 static int park_call_full(struct ast_channel *chan, struct ast_channel *peer, struct ast_park_call_args *args)
01436 {
01437    struct parkeduser *pu = args->pu;
01438    const char *event_from;    /*!< Channel name that is parking the call. */
01439    char app_data[AST_MAX_EXTENSION + AST_MAX_CONTEXT];
01440 
01441    if (pu == NULL) {
01442       args->pu = pu = park_space_reserve(chan, peer, args);
01443       if (pu == NULL) {
01444          return -1;
01445       }
01446    }
01447 
01448    chan->appl = "Parked Call";
01449    chan->data = NULL;
01450 
01451    pu->chan = chan;
01452 
01453    /* Put the parked channel on hold if we have two different channels */
01454    if (chan != peer) {
01455       if (ast_test_flag(args, AST_PARK_OPT_RINGING)) {
01456          pu->hold_method = AST_CONTROL_RINGING;
01457          ast_indicate(chan, AST_CONTROL_RINGING);
01458       } else {
01459          pu->hold_method = AST_CONTROL_HOLD;
01460          ast_indicate_data(chan, AST_CONTROL_HOLD,
01461             S_OR(pu->parkinglot->cfg.mohclass, NULL),
01462             !ast_strlen_zero(pu->parkinglot->cfg.mohclass) ? strlen(pu->parkinglot->cfg.mohclass) + 1 : 0);
01463       }
01464    }
01465    
01466    pu->start = ast_tvnow();
01467    pu->parkingtime = (args->timeout > 0) ? args->timeout : pu->parkinglot->cfg.parkingtime;
01468    if (args->extout)
01469       *(args->extout) = pu->parkingnum;
01470 
01471    if (peer) {
01472       event_from = S_OR(args->orig_chan_name, peer->name);
01473 
01474       /*
01475        * This is so ugly that it hurts, but implementing
01476        * get_base_channel() on local channels could have ugly side
01477        * effects.  We could have
01478        * transferer<->local,1<->local,2<->parking and we need the
01479        * callback name to be that of transferer.  Since local,1/2 have
01480        * the same name we can be tricky and just grab the bridged
01481        * channel from the other side of the local.
01482        */
01483       if (!strcasecmp(peer->tech->type, "Local")) {
01484          struct ast_channel *tmpchan, *base_peer;
01485          char other_side[AST_CHANNEL_NAME];
01486          char *c;
01487 
01488          ast_copy_string(other_side, event_from, sizeof(other_side));
01489          if ((c = strrchr(other_side, ';'))) {
01490             *++c = '1';
01491          }
01492          if ((tmpchan = ast_channel_get_by_name(other_side))) {
01493             ast_channel_lock(tmpchan);
01494             if ((base_peer = ast_bridged_channel(tmpchan))) {
01495                ast_copy_string(pu->peername, base_peer->name, sizeof(pu->peername));
01496             }
01497             ast_channel_unlock(tmpchan);
01498             tmpchan = ast_channel_unref(tmpchan);
01499          }
01500       } else {
01501          ast_copy_string(pu->peername, event_from, sizeof(pu->peername));
01502       }
01503    } else {
01504       event_from = S_OR(pbx_builtin_getvar_helper(chan, "BLINDTRANSFER"), chan->name);
01505    }
01506 
01507    /*
01508     * Remember what had been dialed, so that if the parking
01509     * expires, we try to come back to the same place
01510     */
01511    pu->options_specified = (!ast_strlen_zero(args->return_con) || !ast_strlen_zero(args->return_ext) || args->return_pri);
01512 
01513    /*
01514     * If extension has options specified, they override all other
01515     * possibilities such as the returntoorigin flag and transferred
01516     * context.  Information on extension options is lost here, so
01517     * we set a flag
01518     */
01519    ast_copy_string(pu->context, 
01520       S_OR(args->return_con, S_OR(chan->macrocontext, chan->context)), 
01521       sizeof(pu->context));
01522    ast_copy_string(pu->exten, 
01523       S_OR(args->return_ext, S_OR(chan->macroexten, chan->exten)), 
01524       sizeof(pu->exten));
01525    pu->priority = args->return_pri ? args->return_pri : 
01526       (chan->macropriority ? chan->macropriority : chan->priority);
01527 
01528    /*
01529     * If parking a channel directly, don't quite yet get parking
01530     * running on it.  All parking lot entries are put into the
01531     * parking lot with notquiteyet on.
01532     */
01533    if (peer != chan) {
01534       pu->notquiteyet = 0;
01535    }
01536 
01537    /* Wake up the (presumably select()ing) thread */
01538    pthread_kill(parking_thread, SIGURG);
01539    ast_verb(2, "Parked %s on %d (lot %s). Will timeout back to extension [%s] %s, %d in %d seconds\n",
01540       chan->name, pu->parkingnum, pu->parkinglot->name,
01541       pu->context, pu->exten, pu->priority, (pu->parkingtime / 1000));
01542 
01543    ast_cel_report_event(chan, AST_CEL_PARK_START, NULL, pu->parkinglot->name, peer);
01544 
01545    ast_manager_event(chan, EVENT_FLAG_CALL, "ParkedCall",
01546       "Exten: %s\r\n"
01547       "Channel: %s\r\n"
01548       "Parkinglot: %s\r\n"
01549       "From: %s\r\n"
01550       "Timeout: %ld\r\n"
01551       "CallerIDNum: %s\r\n"
01552       "CallerIDName: %s\r\n"
01553       "ConnectedLineNum: %s\r\n"
01554       "ConnectedLineName: %s\r\n"
01555       "Uniqueid: %s\r\n",
01556       pu->parkingexten, chan->name, pu->parkinglot->name, event_from,
01557       (long)pu->start.tv_sec + (long)(pu->parkingtime/1000) - (long)time(NULL),
01558       S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, "<unknown>"),
01559       S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, "<unknown>"),
01560       S_COR(chan->connected.id.number.valid, chan->connected.id.number.str, "<unknown>"),
01561       S_COR(chan->connected.id.name.valid, chan->connected.id.name.str, "<unknown>"),
01562       chan->uniqueid
01563       );
01564    ast_debug(4, "peer->name: %s\n", peer ? peer->name : "-No peer-");
01565    ast_debug(4, "args->orig_chan_name: %s\n", args->orig_chan_name ? args->orig_chan_name : "-none-");
01566    ast_debug(4, "pu->peername: %s\n", pu->peername);
01567    ast_debug(4, "AMI ParkedCall Channel: %s\n", chan->name);
01568    ast_debug(4, "AMI ParkedCall From: %s\n", event_from);
01569 
01570    if (peer && adsipark && ast_adsi_available(peer)) {
01571       adsi_announce_park(peer, pu->parkingexten);  /* Only supports parking numbers */
01572       ast_adsi_unload_session(peer);
01573    }
01574 
01575    snprintf(app_data, sizeof(app_data), "%s,%s", pu->parkingexten,
01576       pu->parkinglot->name);
01577    if (ast_add_extension(pu->parkinglot->cfg.parking_con, 1, pu->parkingexten, 1,
01578       NULL, NULL, parkedcall, ast_strdup(app_data), ast_free_ptr, registrar)) {
01579       ast_log(LOG_ERROR, "Could not create parked call exten: %s@%s\n",
01580          pu->parkingexten, pu->parkinglot->cfg.parking_con);
01581    } else {
01582       notify_metermaids(pu->parkingexten, pu->parkinglot->cfg.parking_con, AST_DEVICE_INUSE);
01583    }
01584 
01585    AST_LIST_UNLOCK(&pu->parkinglot->parkings);
01586 
01587    /* Only say number if it's a number and the channel hasn't been masqueraded away */
01588    if (peer && !ast_test_flag(args, AST_PARK_OPT_SILENCE)
01589       && (ast_strlen_zero(args->orig_chan_name) || !strcasecmp(peer->name, args->orig_chan_name))) {
01590       /*
01591        * If a channel is masqueraded into peer while playing back the
01592        * parking space number do not continue playing it back.  This
01593        * is the case if an attended transfer occurs.
01594        */
01595       ast_set_flag(peer, AST_FLAG_MASQ_NOSTREAM);
01596       /* Tell the peer channel the number of the parking space */
01597       ast_say_digits(peer, pu->parkingnum, "", peer->language);
01598       ast_clear_flag(peer, AST_FLAG_MASQ_NOSTREAM);
01599    }
01600    if (peer == chan) { /* pu->notquiteyet = 1 */
01601       /* Wake up parking thread if we're really done */
01602       pu->hold_method = AST_CONTROL_HOLD;
01603       ast_indicate_data(chan, AST_CONTROL_HOLD,
01604          S_OR(pu->parkinglot->cfg.mohclass, NULL),
01605          !ast_strlen_zero(pu->parkinglot->cfg.mohclass) ? strlen(pu->parkinglot->cfg.mohclass) + 1 : 0);
01606       pu->notquiteyet = 0;
01607       pthread_kill(parking_thread, SIGURG);
01608    }
01609    return 0;
01610 }
01611 
01612 int ast_park_call_exten(struct ast_channel *park_me, struct ast_channel *parker, const char *park_exten, const char *park_context, int timeout, int *extout)
01613 {
01614    int res;
01615    char *parse;
01616    const char *app_data;
01617    struct ast_exten *exten;
01618    struct park_app_args app_args;
01619    struct ast_park_call_args args = {
01620       .timeout = timeout,
01621       .extout = extout,
01622    };
01623 
01624    if (!park_exten || !park_context) {
01625       return park_call_full(park_me, parker, &args);
01626    }
01627 
01628    /*
01629     * Determiine if the specified park extension has an exclusive
01630     * parking lot to use.
01631     */
01632    if (parker && parker != park_me) {
01633       ast_autoservice_start(park_me);
01634    }
01635    exten = get_parking_exten(park_exten, parker, park_context);
01636    if (exten) {
01637       app_data = ast_get_extension_app_data(exten);
01638       if (!app_data) {
01639          app_data = "";
01640       }
01641       parse = ast_strdupa(app_data);
01642       AST_STANDARD_APP_ARGS(app_args, parse);
01643    
01644       if (!ast_strlen_zero(app_args.pl_name)) {
01645          /* Find the specified exclusive parking lot */
01646          args.parkinglot = find_parkinglot(app_args.pl_name);
01647          if (!args.parkinglot && parkeddynamic) {
01648             args.parkinglot = create_dynamic_parkinglot(app_args.pl_name, park_me);
01649          }
01650       }
01651    }
01652    if (parker && parker != park_me) {
01653       ast_autoservice_stop(park_me);
01654    }
01655 
01656    res = park_call_full(park_me, parker, &args);
01657    if (args.parkinglot) {
01658       parkinglot_unref(args.parkinglot);
01659    }
01660    return res;
01661 }
01662 
01663 int ast_park_call(struct ast_channel *park_me, struct ast_channel *parker, int timeout, const char *park_exten, int *extout)
01664 {
01665    struct ast_park_call_args args = {
01666       .timeout = timeout,
01667       .extout = extout,
01668    };
01669 
01670    return park_call_full(park_me, parker, &args);
01671 }
01672 
01673 /*!
01674  * \brief Park call via masqueraded channel and announce parking spot on peer channel.
01675  *
01676  * \param rchan the real channel to be parked
01677  * \param peer the channel to have the parking read to.
01678  * \param args Additional parking options when parking a call.
01679  *
01680  * \retval 0 on success.
01681  * \retval -1 on failure.
01682  */
01683 static int masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, struct ast_park_call_args *args)
01684 {
01685    struct ast_channel *chan;
01686 
01687    /* Make a new, channel that we'll use to masquerade in the real one */
01688    chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, rchan->accountcode, rchan->exten,
01689       rchan->context, rchan->linkedid, rchan->amaflags, "Parked/%s", rchan->name);
01690    if (!chan) {
01691       ast_log(LOG_WARNING, "Unable to create parked channel\n");
01692       if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
01693          if (peer == rchan) {
01694             /* Only have one channel to worry about. */
01695             ast_stream_and_wait(peer, "pbx-parkingfailed", "");
01696          } else if (peer) {
01697             /* Have two different channels to worry about. */
01698             play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
01699          }
01700       }
01701       return -1;
01702    }
01703 
01704    args->pu = park_space_reserve(rchan, peer, args);
01705    if (!args->pu) {
01706       ast_hangup(chan);
01707       if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
01708          if (peer == rchan) {
01709             /* Only have one channel to worry about. */
01710             ast_stream_and_wait(peer, "pbx-parkingfailed", "");
01711          } else if (peer) {
01712             /* Have two different channels to worry about. */
01713             play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
01714          }
01715       }
01716       return -1;
01717    }
01718 
01719    /* Make formats okay */
01720    chan->readformat = rchan->readformat;
01721    chan->writeformat = rchan->writeformat;
01722 
01723    if (ast_channel_masquerade(chan, rchan)) {
01724       park_space_abort(args->pu);
01725       args->pu = NULL;
01726       ast_hangup(chan);
01727       if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
01728          if (peer == rchan) {
01729             /* Only have one channel to worry about. */
01730             ast_stream_and_wait(peer, "pbx-parkingfailed", "");
01731          } else if (peer) {
01732             /* Have two different channels to worry about. */
01733             play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
01734          }
01735       }
01736       return -1;
01737    }
01738 
01739    /* Setup the extensions and such */
01740    set_c_e_p(chan, rchan->context, rchan->exten, rchan->priority);
01741 
01742    /* Setup the macro extension and such */
01743    ast_copy_string(chan->macrocontext,rchan->macrocontext,sizeof(chan->macrocontext));
01744    ast_copy_string(chan->macroexten,rchan->macroexten,sizeof(chan->macroexten));
01745    chan->macropriority = rchan->macropriority;
01746 
01747    /* Manually do the masquerade to make sure it is complete. */
01748    ast_do_masquerade(chan);
01749 
01750    if (peer == rchan) {
01751       peer = chan;
01752    }
01753 
01754    /* parking space reserved, return code check unnecessary */
01755    park_call_full(chan, peer, args);
01756 
01757    return 0;
01758 }
01759 
01760 int ast_masq_park_call_exten(struct ast_channel *park_me, struct ast_channel *parker, const char *park_exten, const char *park_context, int timeout, int *extout)
01761 {
01762    int res;
01763    char *parse;
01764    const char *app_data;
01765    struct ast_exten *exten;
01766    struct park_app_args app_args;
01767    struct ast_park_call_args args = {
01768       .timeout = timeout,
01769       .extout = extout,
01770    };
01771 
01772    if (parker) {
01773       args.orig_chan_name = ast_strdupa(parker->name);
01774    }
01775    if (!park_exten || !park_context) {
01776       return masq_park_call(park_me, parker, &args);
01777    }
01778 
01779    /*
01780     * Determiine if the specified park extension has an exclusive
01781     * parking lot to use.
01782     */
01783    if (parker && parker != park_me) {
01784       ast_autoservice_start(park_me);
01785    }
01786    exten = get_parking_exten(park_exten, parker, park_context);
01787    if (exten) {
01788       app_data = ast_get_extension_app_data(exten);
01789       if (!app_data) {
01790          app_data = "";
01791       }
01792       parse = ast_strdupa(app_data);
01793       AST_STANDARD_APP_ARGS(app_args, parse);
01794    
01795       if (!ast_strlen_zero(app_args.pl_name)) {
01796          /* Find the specified exclusive parking lot */
01797          args.parkinglot = find_parkinglot(app_args.pl_name);
01798          if (!args.parkinglot && parkeddynamic) {
01799             args.parkinglot = create_dynamic_parkinglot(app_args.pl_name, park_me);
01800          }
01801       }
01802    }
01803    if (parker && parker != park_me) {
01804       ast_autoservice_stop(park_me);
01805    }
01806 
01807    res = masq_park_call(park_me, parker, &args);
01808    if (args.parkinglot) {
01809       parkinglot_unref(args.parkinglot);
01810    }
01811    return res;
01812 }
01813 
01814 int ast_masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout)
01815 {
01816    struct ast_park_call_args args = {
01817       .timeout = timeout,
01818       .extout = extout,
01819    };
01820 
01821    if (peer) {
01822       args.orig_chan_name = ast_strdupa(peer->name);
01823    }
01824    return masq_park_call(rchan, peer, &args);
01825 }
01826 
01827 static int finishup(struct ast_channel *chan)
01828 {
01829    ast_indicate(chan, AST_CONTROL_UNHOLD);
01830 
01831    return ast_autoservice_stop(chan);
01832 }
01833 
01834 /*!
01835  * \internal
01836  * \brief Builtin transfer park call helper.
01837  *
01838  * \param park_me Channel to be parked.
01839  * \param parker Channel parking the call.
01840  * \param park_exten Parking lot dialplan access ramp extension.
01841  *
01842  * \note Assumes park_me is on hold and in autoservice.
01843  *
01844  * \retval -1 on successful park.
01845  * \retval -1 on park_me hangup.
01846  * \retval AST_FEATURE_RETURN_SUCCESS on error to keep the bridge connected.
01847  */
01848 static int xfer_park_call_helper(struct ast_channel *park_me, struct ast_channel *parker, struct ast_exten *park_exten)
01849 {
01850    char *parse;
01851    const char *app_data;
01852    const char *pl_name;
01853    struct ast_park_call_args args = { 0, };
01854    struct park_app_args app_args;
01855    int res;
01856 
01857    app_data = ast_get_extension_app_data(park_exten);
01858    if (!app_data) {
01859       app_data = "";
01860    }
01861    parse = ast_strdupa(app_data);
01862    AST_STANDARD_APP_ARGS(app_args, parse);
01863 
01864    /* Find the parking lot */
01865    if (!ast_strlen_zero(app_args.pl_name)) {
01866       pl_name = app_args.pl_name;
01867    } else {
01868       pl_name = findparkinglotname(parker);
01869    }
01870    if (ast_strlen_zero(pl_name)) {
01871       /* Parking lot is not specified, so use the default parking lot. */
01872       args.parkinglot = parkinglot_addref(default_parkinglot);
01873    } else {
01874       args.parkinglot = find_parkinglot(pl_name);
01875       if (!args.parkinglot && parkeddynamic) {
01876          args.parkinglot = create_dynamic_parkinglot(pl_name, park_me);
01877       }
01878    }
01879 
01880    if (args.parkinglot) {
01881       /* Park the call */
01882       res = finishup(park_me);
01883       if (res) {
01884          /* park_me hungup on us. */
01885          parkinglot_unref(args.parkinglot);
01886          return -1;
01887       }
01888       res = masq_park_call(park_me, parker, &args);
01889       parkinglot_unref(args.parkinglot);
01890    } else {
01891       /* Parking failed because parking lot does not exist. */
01892       if (!ast_test_flag(&args, AST_PARK_OPT_SILENCE)) {
01893          ast_stream_and_wait(parker, "pbx-parkingfailed", "");
01894       }
01895       finishup(park_me);
01896       res = -1;
01897    }
01898 
01899    return res ? AST_FEATURE_RETURN_SUCCESS : -1;
01900 }
01901 
01902 /*!
01903  * \brief set caller and callee according to the direction
01904  * \param caller, callee, peer, chan, sense
01905  *
01906  * Detect who triggered feature and set callee/caller variables accordingly
01907  */
01908 static void set_peers(struct ast_channel **caller, struct ast_channel **callee,
01909    struct ast_channel *peer, struct ast_channel *chan, int sense)
01910 {
01911    if (sense == FEATURE_SENSE_PEER) {
01912       *caller = peer;
01913       *callee = chan;
01914    } else {
01915       *callee = peer;
01916       *caller = chan;
01917    }
01918 }
01919 
01920 /*!
01921  * \brief support routing for one touch call parking
01922  * \param chan channel parking call
01923  * \param peer channel to be parked
01924  * \param config unsed
01925  * \param code unused
01926  * \param sense feature options
01927  * \param data unused
01928  *
01929  * \retval -1 on successful park.
01930  * \retval -1 on chan hangup.
01931  * \retval AST_FEATURE_RETURN_SUCCESS on error to keep the bridge connected.
01932  */
01933 static int builtin_parkcall(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
01934 {
01935    struct ast_channel *parker;
01936    struct ast_channel *parkee;
01937    struct ast_park_call_args args = { 0, };
01938 
01939    /*
01940     * We used to set chan's exten and priority to "s" and 1 here,
01941     * but this generates (in some cases) an invalid extension, and
01942     * if "s" exists, could errantly cause execution of extensions
01943     * you don't expect.  It makes more sense to let nature take its
01944     * course when chan finishes, and let the pbx do its thing and
01945     * hang up when the park is over.
01946     */
01947 
01948    /* Answer if call is not up */
01949    if (chan->_state != AST_STATE_UP) {
01950       /*
01951        * XXX Why are we doing this?  Both of the channels should be up
01952        * since you cannot do DTMF features unless you are bridged.
01953        */
01954       if (ast_answer(chan)) {
01955          return -1;
01956       }
01957 
01958       /* Sleep to allow VoIP streams to settle down */
01959       if (ast_safe_sleep(chan, 1000)) {
01960          return -1;
01961       }
01962    }
01963 
01964    /* one direction used to call park_call.... */
01965    set_peers(&parker, &parkee, peer, chan, sense);
01966    return masq_park_call(parkee, parker, &args) ? AST_FEATURE_RETURN_SUCCESS : -1;
01967 }
01968 
01969 /*!
01970  * \internal
01971  * \brief Play file to specified channel.
01972  *
01973  * \param play_to Channel to play audiofile to.
01974  * \param other Channel to put in autoservice while playing file.
01975  * \param msg Descriptive name of message type being played.
01976  * \param audiofile Audio file to play.
01977  *
01978  * \retval 0 on success.
01979  * \retval -1 on error. (Couldn't play file, a channel hung up,...)
01980  */
01981 static int play_message_on_chan(struct ast_channel *play_to, struct ast_channel *other, const char *msg, const char *audiofile)
01982 {
01983    /* Put other channel in autoservice. */
01984    if (ast_autoservice_start(other)) {
01985       return -1;
01986    }
01987    ast_autoservice_ignore(other, AST_FRAME_DTMF_BEGIN);
01988    ast_autoservice_ignore(other, AST_FRAME_DTMF_END);
01989    if (ast_stream_and_wait(play_to, audiofile, "")) {
01990       ast_log(LOG_WARNING, "Failed to play %s '%s'!\n", msg, audiofile);
01991       ast_autoservice_stop(other);
01992       return -1;
01993    }
01994    if (ast_autoservice_stop(other)) {
01995       return -1;
01996    }
01997    return 0;
01998 }
01999 
02000 /*!
02001  * \internal
02002  * \brief Play file to specified channels.
02003  *
02004  * \param left Channel on left to play file.
02005  * \param right Channel on right to play file.
02006  * \param which Play file on indicated channels: which < 0 play left, which == 0 play both, which > 0 play right
02007  * \param msg Descriptive name of message type being played.
02008  * \param audiofile Audio file to play to channels.
02009  *
02010  * \note Plays file to the indicated channels in turn so please
02011  * don't use this for very long messages.
02012  *
02013  * \retval 0 on success.
02014  * \retval -1 on error. (Couldn't play file, channel hung up,...)
02015  */
02016 static int play_message_to_chans(struct ast_channel *left, struct ast_channel *right, int which, const char *msg, const char *audiofile)
02017 {
02018    /* First play the file to the left channel if requested. */
02019    if (which <= 0 && play_message_on_chan(left, right, msg, audiofile)) {
02020       return -1;
02021    }
02022 
02023    /* Then play the file to the right channel if requested. */
02024    if (which >= 0 && play_message_on_chan(right, left, msg, audiofile)) {
02025       return -1;
02026    }
02027 
02028    return 0;
02029 }
02030 
02031 /*!
02032  * \brief Play message to both caller and callee in bridged call, plays synchronously, autoservicing the
02033  * other channel during the message, so please don't use this for very long messages
02034  */
02035 static int play_message_in_bridged_call(struct ast_channel *caller_chan, struct ast_channel *callee_chan, const char *audiofile)
02036 {
02037    return play_message_to_chans(caller_chan, callee_chan, 0, "automon message",
02038       audiofile);
02039 }
02040 
02041 /*!
02042  * \brief Monitor a channel by DTMF
02043  * \param chan channel requesting monitor
02044  * \param peer channel to be monitored
02045  * \param config
02046  * \param code
02047  * \param sense feature options
02048  *
02049  * \param data
02050  * Check monitor app enabled, setup channels, both caller/callee chans not null
02051  * get TOUCH_MONITOR variable for filename if exists, exec monitor app.
02052  * \retval AST_FEATURE_RETURN_SUCCESS on success.
02053  * \retval -1 on error.
02054  */
02055 static int builtin_automonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
02056 {
02057    char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
02058    int x = 0;
02059    size_t len;
02060    struct ast_channel *caller_chan, *callee_chan;
02061    const char *automon_message_start = NULL;
02062    const char *automon_message_stop = NULL;
02063    const char *touch_format = NULL;
02064    const char *touch_monitor = NULL;
02065    const char *touch_monitor_prefix = NULL;
02066 
02067    if (!monitor_ok) {
02068       ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
02069       return -1;
02070    }
02071 
02072    if (!monitor_app && !(monitor_app = pbx_findapp("Monitor"))) {
02073       monitor_ok = 0;
02074       ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
02075       return -1;
02076    }
02077 
02078    set_peers(&caller_chan, &callee_chan, peer, chan, sense);
02079 
02080    /* Find extra messages */
02081    automon_message_start = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_START");
02082    automon_message_stop = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_STOP");
02083 
02084    if (!ast_strlen_zero(courtesytone)) {  /* Play courtesy tone if configured */
02085       if(play_message_in_bridged_call(caller_chan, callee_chan, courtesytone) == -1) {
02086          return -1;
02087       }
02088    }
02089    
02090    if (callee_chan->monitor) {
02091       ast_verb(4, "User hit '%s' to stop recording call.\n", code);
02092       if (!ast_strlen_zero(automon_message_stop)) {
02093          play_message_in_bridged_call(caller_chan, callee_chan, automon_message_stop);
02094       }
02095       callee_chan->monitor->stop(callee_chan, 1);
02096       return AST_FEATURE_RETURN_SUCCESS;
02097    }
02098 
02099    touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_FORMAT");
02100    touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR");
02101    touch_monitor_prefix = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_PREFIX");
02102 
02103    if (!touch_format)
02104       touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_FORMAT");
02105 
02106    if (!touch_monitor)
02107       touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR");
02108 
02109    if (!touch_monitor_prefix)
02110       touch_monitor_prefix = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_PREFIX");
02111 
02112    if (touch_monitor) {
02113       len = strlen(touch_monitor) + 50;
02114       args = alloca(len);
02115       touch_filename = alloca(len);
02116       snprintf(touch_filename, len, "%s-%ld-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), touch_monitor);
02117       snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
02118    } else {
02119       caller_chan_id = ast_strdupa(S_COR(caller_chan->caller.id.number.valid,
02120          caller_chan->caller.id.number.str, caller_chan->name));
02121       callee_chan_id = ast_strdupa(S_COR(callee_chan->caller.id.number.valid,
02122          callee_chan->caller.id.number.str, callee_chan->name));
02123       len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
02124       args = alloca(len);
02125       touch_filename = alloca(len);
02126       snprintf(touch_filename, len, "%s-%ld-%s-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), caller_chan_id, callee_chan_id);
02127       snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
02128    }
02129 
02130    for(x = 0; x < strlen(args); x++) {
02131       if (args[x] == '/')
02132          args[x] = '-';
02133    }
02134    
02135    ast_verb(4, "User hit '%s' to record call. filename: %s\n", code, args);
02136 
02137    pbx_exec(callee_chan, monitor_app, args);
02138    pbx_builtin_setvar_helper(callee_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
02139    pbx_builtin_setvar_helper(caller_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
02140 
02141    if (!ast_strlen_zero(automon_message_start)) {  /* Play start message for both channels */
02142       play_message_in_bridged_call(caller_chan, callee_chan, automon_message_start);
02143    }
02144 
02145    return AST_FEATURE_RETURN_SUCCESS;
02146 }
02147 
02148 static int builtin_automixmonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
02149 {
02150    char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
02151    int x = 0;
02152    size_t len;
02153    struct ast_channel *caller_chan, *callee_chan;
02154    const char *mixmonitor_spy_type = "MixMonitor";
02155    const char *touch_format;
02156    const char *touch_monitor;
02157    int count = 0;
02158 
02159    if (!mixmonitor_ok) {
02160       ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
02161       return -1;
02162    }
02163 
02164    if (!(mixmonitor_app = pbx_findapp("MixMonitor"))) {
02165       mixmonitor_ok = 0;
02166       ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
02167       return -1;
02168    }
02169 
02170    set_peers(&caller_chan, &callee_chan, peer, chan, sense);
02171 
02172    if (!ast_strlen_zero(courtesytone)) {
02173       if (ast_autoservice_start(callee_chan))
02174          return -1;
02175       ast_autoservice_ignore(callee_chan, AST_FRAME_DTMF_END);
02176       if (ast_stream_and_wait(caller_chan, courtesytone, "")) {
02177          ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
02178          ast_autoservice_stop(callee_chan);
02179          return -1;
02180       }
02181       if (ast_autoservice_stop(callee_chan))
02182          return -1;
02183    }
02184 
02185    ast_channel_lock(callee_chan);
02186    count = ast_channel_audiohook_count_by_source(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
02187    ast_channel_unlock(callee_chan);
02188 
02189    /* This means a mixmonitor is attached to the channel, running or not is unknown. */
02190    if (count > 0) {
02191       ast_verb(3, "User hit '%s' to stop recording call.\n", code);
02192 
02193       /* Make sure they are running */
02194       ast_channel_lock(callee_chan);
02195       count = ast_channel_audiohook_count_by_source_running(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
02196       ast_channel_unlock(callee_chan);
02197       if (count > 0) {
02198          if (!stopmixmonitor_ok) {
02199             ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
02200             return -1;
02201          }
02202          if (!(stopmixmonitor_app = pbx_findapp("StopMixMonitor"))) {
02203             stopmixmonitor_ok = 0;
02204             ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
02205             return -1;
02206          } else {
02207             pbx_exec(callee_chan, stopmixmonitor_app, "");
02208             return AST_FEATURE_RETURN_SUCCESS;
02209          }
02210       }
02211       
02212       ast_log(LOG_WARNING,"Stopped MixMonitors are attached to the channel.\n"); 
02213    }        
02214 
02215    touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR_FORMAT");
02216    touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR");
02217 
02218    if (!touch_format)
02219       touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR_FORMAT");
02220 
02221    if (!touch_monitor)
02222       touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR");
02223 
02224    if (touch_monitor) {
02225       len = strlen(touch_monitor) + 50;
02226       args = alloca(len);
02227       touch_filename = alloca(len);
02228       snprintf(touch_filename, len, "auto-%ld-%s", (long)time(NULL), touch_monitor);
02229       snprintf(args, len, "%s.%s,b", touch_filename, (touch_format) ? touch_format : "wav");
02230    } else {
02231       caller_chan_id = ast_strdupa(S_COR(caller_chan->caller.id.number.valid,
02232          caller_chan->caller.id.number.str, caller_chan->name));
02233       callee_chan_id = ast_strdupa(S_COR(callee_chan->caller.id.number.valid,
02234          callee_chan->caller.id.number.str, callee_chan->name));
02235       len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
02236       args = alloca(len);
02237       touch_filename = alloca(len);
02238       snprintf(touch_filename, len, "auto-%ld-%s-%s", (long)time(NULL), caller_chan_id, callee_chan_id);
02239       snprintf(args, len, "%s.%s,b", touch_filename, S_OR(touch_format, "wav"));
02240    }
02241 
02242    for( x = 0; x < strlen(args); x++) {
02243       if (args[x] == '/')
02244          args[x] = '-';
02245    }
02246 
02247    ast_verb(3, "User hit '%s' to record call. filename: %s\n", code, touch_filename);
02248 
02249    pbx_exec(callee_chan, mixmonitor_app, args);
02250    pbx_builtin_setvar_helper(callee_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
02251    pbx_builtin_setvar_helper(caller_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
02252    return AST_FEATURE_RETURN_SUCCESS;
02253 }
02254 
02255 static int builtin_disconnect(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
02256 {
02257    ast_verb(4, "User hit '%s' to disconnect call.\n", code);
02258    return AST_FEATURE_RETURN_HANGUP;
02259 }
02260 
02261 /*!
02262  * \brief Find the context for the transfer
02263  * \param transferer
02264  * \param transferee
02265  * 
02266  * Grab the TRANSFER_CONTEXT, if fails try grabbing macrocontext.
02267  * \return a context string
02268  */
02269 static const char *real_ctx(struct ast_channel *transferer, struct ast_channel *transferee)
02270 {
02271    const char *s = pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT");
02272    if (ast_strlen_zero(s)) {
02273       s = pbx_builtin_getvar_helper(transferee, "TRANSFER_CONTEXT");
02274    }
02275    if (ast_strlen_zero(s)) { /* Use the non-macro context to transfer the call XXX ? */
02276       s = transferer->macrocontext;
02277    }
02278    if (ast_strlen_zero(s)) {
02279       s = transferer->context;
02280    }
02281    return s;  
02282 }
02283 
02284 /*!
02285  * \brief Blind transfer user to another extension
02286  * \param chan channel to be transfered
02287  * \param peer channel initiated blind transfer
02288  * \param config
02289  * \param code
02290  * \param data
02291  * \param sense  feature options
02292  * 
02293  * Place chan on hold, check if transferred to parkinglot extension,
02294  * otherwise check extension exists and transfer caller.
02295  * \retval AST_FEATURE_RETURN_SUCCESS.
02296  * \retval -1 on failure.
02297  */
02298 static int builtin_blindtransfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
02299 {
02300    struct ast_channel *transferer;
02301    struct ast_channel *transferee;
02302    struct ast_exten *park_exten;
02303    const char *transferer_real_context;
02304    char xferto[256] = "";
02305    int res;
02306 
02307    ast_debug(1, "Executing Blind Transfer %s, %s (sense=%d) \n", chan->name, peer->name, sense);
02308    set_peers(&transferer, &transferee, peer, chan, sense);
02309    transferer_real_context = real_ctx(transferer, transferee);
02310 
02311    /* Start autoservice on transferee while we talk to the transferer */
02312    ast_autoservice_start(transferee);
02313    ast_indicate(transferee, AST_CONTROL_HOLD);
02314 
02315    /* Transfer */
02316    res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
02317    if (res < 0) {
02318       finishup(transferee);
02319       return -1; /* error ? */
02320    }
02321    if (res > 0) { /* If they've typed a digit already, handle it */
02322       xferto[0] = (char) res;
02323    }
02324 
02325    res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
02326    if (res < 0) {  /* hangup or error, (would be 0 for invalid and 1 for valid) */
02327       finishup(transferee);
02328       return -1;
02329    }
02330    if (res == 0) {
02331       if (xferto[0]) {
02332          ast_log(LOG_WARNING, "Extension '%s' does not exist in context '%s'\n",
02333             xferto, transferer_real_context);
02334       } else {
02335          /* Does anyone care about this case? */
02336          ast_log(LOG_WARNING, "No digits dialed.\n");
02337       }
02338       ast_stream_and_wait(transferer, "pbx-invalid", "");
02339       finishup(transferee);
02340       return AST_FEATURE_RETURN_SUCCESS;
02341    }
02342 
02343    park_exten = get_parking_exten(xferto, transferer, transferer_real_context);
02344    if (park_exten) {
02345       /* We are transfering the transferee to a parking lot. */
02346       return xfer_park_call_helper(transferee, transferer, park_exten);
02347    }
02348 
02349    /* Do blind transfer. */
02350    ast_verb(3, "Blind transferring %s to '%s' (context %s) priority 1\n",
02351       transferee->name, xferto, transferer_real_context);
02352    ast_cel_report_event(transferer, AST_CEL_BLINDTRANSFER, NULL, xferto, transferee);
02353    pbx_builtin_setvar_helper(transferer, "BLINDTRANSFER", transferee->name);
02354    pbx_builtin_setvar_helper(transferee, "BLINDTRANSFER", transferer->name);
02355    finishup(transferee);
02356    ast_channel_lock(transferer);
02357    if (!transferer->cdr) { /* this code should never get called (in a perfect world) */
02358       transferer->cdr = ast_cdr_alloc();
02359       if (transferer->cdr) {
02360          ast_cdr_init(transferer->cdr, transferer); /* initialize our channel's cdr */
02361          ast_cdr_start(transferer->cdr);
02362       }
02363    }
02364    ast_channel_unlock(transferer);
02365    if (transferer->cdr) {
02366       struct ast_cdr *swap = transferer->cdr;
02367 
02368       ast_debug(1,
02369          "transferer=%s; transferee=%s; lastapp=%s; lastdata=%s; chan=%s; dstchan=%s\n",
02370          transferer->name, transferee->name, transferer->cdr->lastapp,
02371          transferer->cdr->lastdata, transferer->cdr->channel,
02372          transferer->cdr->dstchannel);
02373       ast_debug(1, "TRANSFEREE; lastapp=%s; lastdata=%s, chan=%s; dstchan=%s\n",
02374          transferee->cdr->lastapp, transferee->cdr->lastdata, transferee->cdr->channel,
02375          transferee->cdr->dstchannel);
02376       ast_debug(1, "transferer_real_context=%s; xferto=%s\n",
02377          transferer_real_context, xferto);
02378       /* swap cdrs-- it will save us some time & work */
02379       transferer->cdr = transferee->cdr;
02380       transferee->cdr = swap;
02381    }
02382    if (!transferee->pbx) {
02383       /* Doh!  Use our handy async_goto functions */
02384       ast_debug(1, "About to ast_async_goto %s.\n", transferee->name);
02385       if (ast_async_goto(transferee, transferer_real_context, xferto, 1)) {
02386          ast_log(LOG_WARNING, "Async goto failed :-(\n");
02387       }
02388 
02389       /* The transferee is masqueraded and the original bridged channels can be hungup. */
02390       res = -1;
02391    } else {
02392       /* Set the transferee's new extension, since it exists, using transferer context */
02393       ast_debug(1, "About to explicit goto %s, it has a PBX.\n", transferee->name);
02394       ast_set_flag(transferee, AST_FLAG_BRIDGE_HANGUP_DONT); /* don't let the after-bridge code run the h-exten */
02395       set_c_e_p(transferee, transferer_real_context, xferto, 0);
02396 
02397       /*
02398        * Break the bridge.  The transferee needs to resume executing
02399        * dialplan at the xferto location.
02400        */
02401       res = AST_FEATURE_RETURN_SUCCESSBREAK;
02402    }
02403    check_goto_on_transfer(transferer);
02404    return res;
02405 }
02406 
02407 /*!
02408  * \brief make channels compatible
02409  * \param c
02410  * \param newchan
02411  * \retval 0 on success.
02412  * \retval -1 on failure.
02413  */
02414 static int check_compat(struct ast_channel *c, struct ast_channel *newchan)
02415 {
02416    if (ast_channel_make_compatible(c, newchan) < 0) {
02417       ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n",
02418          c->name, newchan->name);
02419       ast_hangup(newchan);
02420       return -1;
02421    }
02422    return 0;
02423 }
02424 
02425 /*!
02426  * \internal
02427  * \brief Builtin attended transfer failed cleanup.
02428  * \since 1.10
02429  *
02430  * \param transferee Party A in the transfer.
02431  * \param transferer Party B in the transfer.
02432  * \param connected_line Saved connected line info about party A.
02433  *
02434  * \note The connected_line data is freed.
02435  *
02436  * \return Nothing
02437  */
02438 static void atxfer_fail_cleanup(struct ast_channel *transferee, struct ast_channel *transferer, struct ast_party_connected_line *connected_line)
02439 {
02440    finishup(transferee);
02441 
02442    /*
02443     * Restore party B connected line info about party A.
02444     *
02445     * Party B was the caller to party C and is the last known mode
02446     * for party B.
02447     */
02448    if (ast_channel_connected_line_macro(transferee, transferer, connected_line, 1, 0)) {
02449       ast_channel_update_connected_line(transferer, connected_line, NULL);
02450    }
02451    ast_party_connected_line_free(connected_line);
02452 }
02453 
02454 /*!
02455  * \brief Attended transfer
02456  * \param chan transfered user
02457  * \param peer person transfering call
02458  * \param config
02459  * \param code
02460  * \param sense feature options
02461  *
02462  * \param data
02463  * Get extension to transfer to, if you cannot generate channel (or find extension)
02464  * return to host channel. After called channel answered wait for hangup of transferer,
02465  * bridge call between transfer peer (taking them off hold) to attended transfer channel.
02466  *
02467  * \return -1 on failure
02468  */
02469 static int builtin_atxfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
02470 {
02471    struct ast_channel *transferer;/* Party B */
02472    struct ast_channel *transferee;/* Party A */
02473    struct ast_exten *park_exten;
02474    const char *chan1_attended_sound;
02475    const char *chan2_attended_sound;
02476    const char *transferer_real_context;
02477    char xferto[256] = "";
02478    int res;
02479    int outstate=0;
02480    struct ast_channel *newchan;
02481    struct ast_channel *xferchan;
02482    struct ast_bridge_thread_obj *tobj;
02483    struct ast_bridge_config bconfig;
02484    int l;
02485    struct ast_party_connected_line connected_line;
02486    struct ast_datastore *features_datastore;
02487    struct ast_dial_features *dialfeatures;
02488    char *transferer_tech;
02489    char *transferer_name;
02490    char *transferer_name_orig;
02491    char *dash;
02492 
02493    ast_debug(1, "Executing Attended Transfer %s, %s (sense=%d) \n", chan->name, peer->name, sense);
02494    set_peers(&transferer, &transferee, peer, chan, sense);
02495    transferer_real_context = real_ctx(transferer, transferee);
02496 
02497    /* Start autoservice on transferee while we talk to the transferer */
02498    ast_autoservice_start(transferee);
02499    ast_indicate(transferee, AST_CONTROL_HOLD);
02500 
02501    /* Transfer */
02502    res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
02503    if (res < 0) {
02504       finishup(transferee);
02505       return -1;
02506    }
02507    if (res > 0) { /* If they've typed a digit already, handle it */
02508       xferto[0] = (char) res;
02509    }
02510 
02511    /* this is specific of atxfer */
02512    res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
02513    if (res < 0) {  /* hangup or error, (would be 0 for invalid and 1 for valid) */
02514       finishup(transferee);
02515       return -1;
02516    }
02517    l = strlen(xferto);
02518    if (res == 0) {
02519       if (l) {
02520          ast_log(LOG_WARNING, "Extension '%s' does not exist in context '%s'\n",
02521             xferto, transferer_real_context);
02522       } else {
02523          /* Does anyone care about this case? */
02524          ast_log(LOG_WARNING, "No digits dialed for atxfer.\n");
02525       }
02526       ast_stream_and_wait(transferer, "pbx-invalid", "");
02527       finishup(transferee);
02528       return AST_FEATURE_RETURN_SUCCESS;
02529    }
02530 
02531    park_exten = get_parking_exten(xferto, transferer, transferer_real_context);
02532    if (park_exten) {
02533       /* We are transfering the transferee to a parking lot. */
02534       return xfer_park_call_helper(transferee, transferer, park_exten);
02535    }
02536 
02537    /*
02538     * Append context to dialed transfer number.
02539     *
02540     * NOTE: The local channel needs the /n flag so party C will use
02541     * the feature flags set by the dialplan when calling that
02542     * party.
02543     */
02544    snprintf(xferto + l, sizeof(xferto) - l, "@%s/n", transferer_real_context);
02545 
02546    /* If we are performing an attended transfer and we have two channels involved then
02547       copy sound file information to play upon attended transfer completion */
02548    chan1_attended_sound = pbx_builtin_getvar_helper(transferer, "ATTENDED_TRANSFER_COMPLETE_SOUND");
02549    chan2_attended_sound = pbx_builtin_getvar_helper(transferee, "ATTENDED_TRANSFER_COMPLETE_SOUND");
02550    if (!ast_strlen_zero(chan1_attended_sound)) {
02551       pbx_builtin_setvar_helper(transferer, "BRIDGE_PLAY_SOUND", chan1_attended_sound);
02552    }
02553    if (!ast_strlen_zero(chan2_attended_sound)) {
02554       pbx_builtin_setvar_helper(transferee, "BRIDGE_PLAY_SOUND", chan2_attended_sound);
02555    }
02556 
02557    /* Extract redial transferer information from the channel name. */
02558    transferer_name_orig = ast_strdupa(transferer->name);
02559    transferer_name = ast_strdupa(transferer_name_orig);
02560    transferer_tech = strsep(&transferer_name, "/");
02561    dash = strrchr(transferer_name, '-');
02562    if (dash) {
02563       /* Trim off channel name sequence/serial number. */
02564       *dash = '\0';
02565    }
02566 
02567    /* Stop autoservice so we can monitor all parties involved in the transfer. */
02568    if (ast_autoservice_stop(transferee) < 0) {
02569       ast_indicate(transferee, AST_CONTROL_UNHOLD);
02570       return -1;
02571    }
02572 
02573    /* Save connected line info for party B about party A in case transfer fails. */
02574    ast_party_connected_line_init(&connected_line);
02575    ast_channel_lock(transferer);
02576    ast_party_connected_line_copy(&connected_line, &transferer->connected);
02577    ast_channel_unlock(transferer);
02578    connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
02579 
02580    /* Dial party C */
02581    newchan = feature_request_and_dial(transferer, transferer_name_orig, transferer,
02582       transferee, "Local", ast_best_codec(transferer->nativeformats), xferto,
02583       atxfernoanswertimeout, &outstate, transferer->language);
02584    ast_debug(2, "Dial party C result: newchan:%d, outstate:%d\n", !!newchan, outstate);
02585 
02586    if (!ast_check_hangup(transferer)) {
02587       int hangup_dont = 0;
02588 
02589       /* Transferer (party B) is up */
02590       ast_debug(1, "Actually doing an attended transfer.\n");
02591 
02592       /* Start autoservice on transferee while the transferer deals with party C. */
02593       ast_autoservice_start(transferee);
02594 
02595       ast_indicate(transferer, -1);
02596       if (!newchan) {
02597          /* any reason besides user requested cancel and busy triggers the failed sound */
02598          switch (outstate) {
02599          case AST_CONTROL_UNHOLD:/* Caller requested cancel or party C answer timeout. */
02600          case AST_CONTROL_BUSY:
02601          case AST_CONTROL_CONGESTION:
02602             if (ast_stream_and_wait(transferer, xfersound, "")) {
02603                ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
02604             }
02605             break;
02606          default:
02607             if (ast_stream_and_wait(transferer, xferfailsound, "")) {
02608                ast_log(LOG_WARNING, "Failed to play transfer failed sound!\n");
02609             }
02610             break;
02611          }
02612          atxfer_fail_cleanup(transferee, transferer, &connected_line);
02613          return AST_FEATURE_RETURN_SUCCESS;
02614       }
02615 
02616       if (check_compat(transferer, newchan)) {
02617          if (ast_stream_and_wait(transferer, xferfailsound, "")) {
02618             ast_log(LOG_WARNING, "Failed to play transfer failed sound!\n");
02619          }
02620          atxfer_fail_cleanup(transferee, transferer, &connected_line);
02621          return AST_FEATURE_RETURN_SUCCESS;
02622       }
02623       memset(&bconfig,0,sizeof(struct ast_bridge_config));
02624       ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
02625       ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
02626 
02627       /*
02628        * ast_bridge_call clears AST_FLAG_BRIDGE_HANGUP_DONT, but we
02629        * don't want that to happen here because the transferer is in
02630        * another bridge already.
02631        */
02632       if (ast_test_flag(transferer, AST_FLAG_BRIDGE_HANGUP_DONT)) {
02633          hangup_dont = 1;
02634       }
02635 
02636       /*
02637        * Don't let the after-bridge code run the h-exten.  It is the
02638        * wrong bridge to run the h-exten after.
02639        */
02640       ast_set_flag(transferer, AST_FLAG_BRIDGE_HANGUP_DONT);
02641 
02642       /*
02643        * Let party B and C talk as long as they want while party A
02644        * languishes in autoservice listening to MOH.
02645        */
02646       ast_bridge_call(transferer, newchan, &bconfig);
02647 
02648       if (hangup_dont) {
02649          /* Restore the AST_FLAG_BRIDGE_HANGUP_DONT flag */
02650          ast_set_flag(transferer, AST_FLAG_BRIDGE_HANGUP_DONT);
02651       }
02652 
02653       if (ast_check_hangup(newchan) || !ast_check_hangup(transferer)) {
02654          ast_hangup(newchan);
02655          if (ast_stream_and_wait(transferer, xfersound, "")) {
02656             ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
02657          }
02658          atxfer_fail_cleanup(transferee, transferer, &connected_line);
02659          return AST_FEATURE_RETURN_SUCCESS;
02660       }
02661 
02662       /* Transferer (party B) is confirmed hung up at this point. */
02663       if (check_compat(transferee, newchan)) {
02664          finishup(transferee);
02665          ast_party_connected_line_free(&connected_line);
02666          return -1;
02667       }
02668 
02669       ast_indicate(transferee, AST_CONTROL_UNHOLD);
02670       if ((ast_autoservice_stop(transferee) < 0)
02671          || (ast_waitfordigit(transferee, 100) < 0)
02672          || (ast_waitfordigit(newchan, 100) < 0)
02673          || ast_check_hangup(transferee)
02674          || ast_check_hangup(newchan)) {
02675          ast_hangup(newchan);
02676          ast_party_connected_line_free(&connected_line);
02677          return -1;
02678       }
02679    } else if (!ast_check_hangup(transferee)) {
02680       /* Transferer (party B) has hung up at this point.  Doing blonde transfer. */
02681       ast_debug(1, "Actually doing a blonde transfer.\n");
02682 
02683       if (!newchan && !atxferdropcall) {
02684          /* Party C is not available, try to call party B back. */
02685          unsigned int tries = 0;
02686 
02687          if (ast_strlen_zero(transferer_name) || ast_strlen_zero(transferer_tech)) {
02688             ast_log(LOG_WARNING,
02689                "Transferer channel name: '%s' cannot be used for callback.\n",
02690                transferer_name_orig);
02691             ast_indicate(transferee, AST_CONTROL_UNHOLD);
02692             ast_party_connected_line_free(&connected_line);
02693             return -1;
02694          }
02695 
02696          tries = 0;
02697          for (;;) {
02698             /* Try to get party B back. */
02699             ast_debug(1, "We're trying to callback %s/%s\n",
02700                transferer_tech, transferer_name);
02701             newchan = feature_request_and_dial(transferer, transferer_name_orig,
02702                transferee, transferee, transferer_tech,
02703                ast_best_codec(transferee->nativeformats), transferer_name,
02704                atxfernoanswertimeout, &outstate, transferer->language);
02705             ast_debug(2, "Dial party B result: newchan:%d, outstate:%d\n",
02706                !!newchan, outstate);
02707             if (newchan) {
02708                /*
02709                 * We have recalled party B (newchan).  We need to give this
02710                 * call leg the same feature flags as the original party B call
02711                 * leg.
02712                 */
02713                ast_channel_lock(transferer);
02714                features_datastore = ast_channel_datastore_find(transferer,
02715                   &dial_features_info, NULL);
02716                if (features_datastore && (dialfeatures = features_datastore->data)) {
02717                   struct ast_flags my_features = { 0 };
02718                   struct ast_flags peer_features = { 0 };
02719 
02720                   ast_copy_flags(&my_features, &dialfeatures->my_features,
02721                      AST_FLAGS_ALL);
02722                   ast_copy_flags(&peer_features, &dialfeatures->peer_features,
02723                      AST_FLAGS_ALL);
02724                   ast_channel_unlock(transferer);
02725                   add_features_datastore(newchan, &my_features, &peer_features);
02726                } else {
02727                   ast_channel_unlock(transferer);
02728                }
02729                break;
02730             }
02731             if (ast_check_hangup(transferee)) {
02732                break;
02733             }
02734 
02735             ++tries;
02736             if (atxfercallbackretries <= tries) {
02737                /* No more callback tries remaining. */
02738                break;
02739             }
02740 
02741             if (atxferloopdelay) {
02742                /* Transfer failed, sleeping */
02743                ast_debug(1, "Sleeping for %d ms before retrying atxfer.\n",
02744                   atxferloopdelay);
02745                ast_safe_sleep(transferee, atxferloopdelay);
02746                if (ast_check_hangup(transferee)) {
02747                   ast_party_connected_line_free(&connected_line);
02748                   return -1;
02749                }
02750             }
02751 
02752             /* Retry dialing party C. */
02753             ast_debug(1, "We're retrying to call %s/%s\n", "Local", xferto);
02754             newchan = feature_request_and_dial(transferer, transferer_name_orig,
02755                transferer, transferee, "Local",
02756                ast_best_codec(transferee->nativeformats), xferto,
02757                atxfernoanswertimeout, &outstate, transferer->language);
02758             ast_debug(2, "Redial party C result: newchan:%d, outstate:%d\n",
02759                !!newchan, outstate);
02760             if (newchan || ast_check_hangup(transferee)) {
02761                break;
02762             }
02763          }
02764       }
02765       ast_indicate(transferee, AST_CONTROL_UNHOLD);
02766       if (!newchan) {
02767          /* No party C or could not callback party B. */
02768          ast_party_connected_line_free(&connected_line);
02769          return -1;
02770       }
02771 
02772       /* newchan is up, we should prepare transferee and bridge them */
02773       if (ast_check_hangup(newchan)) {
02774          ast_hangup(newchan);
02775          ast_party_connected_line_free(&connected_line);
02776          return -1;
02777       }
02778       if (check_compat(transferee, newchan)) {
02779          ast_party_connected_line_free(&connected_line);
02780          return -1;
02781       }
02782    } else {
02783       /*
02784        * Both the transferer and transferee have hungup.  If newchan
02785        * is up, hang it up as it has no one to talk to.
02786        */
02787       ast_debug(1, "Everyone is hungup.\n");
02788       if (newchan) {
02789          ast_hangup(newchan);
02790       }
02791       ast_party_connected_line_free(&connected_line);
02792       return -1;
02793    }
02794 
02795    /* Initiate the channel transfer of party A to party C (or recalled party B). */
02796    ast_cel_report_event(transferee, AST_CEL_ATTENDEDTRANSFER, NULL, NULL, newchan);
02797 
02798    xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", transferee->linkedid, 0, "Transfered/%s", transferee->name);
02799    if (!xferchan) {
02800       ast_hangup(newchan);
02801       ast_party_connected_line_free(&connected_line);
02802       return -1;
02803    }
02804 
02805    /* Give party A a momentary ringback tone during transfer. */
02806    xferchan->visible_indication = AST_CONTROL_RINGING;
02807 
02808    /* Make formats okay */
02809    xferchan->readformat = transferee->readformat;
02810    xferchan->writeformat = transferee->writeformat;
02811 
02812    if (ast_channel_masquerade(xferchan, transferee)) {
02813       ast_hangup(xferchan);
02814       ast_hangup(newchan);
02815       ast_party_connected_line_free(&connected_line);
02816       return -1;
02817    }
02818    ast_explicit_goto(xferchan, transferee->context, transferee->exten, transferee->priority);
02819    xferchan->_state = AST_STATE_UP;
02820    ast_clear_flag(xferchan, AST_FLAGS_ALL);
02821 
02822    /* Do the masquerade manually to make sure that is is completed. */
02823    ast_do_masquerade(xferchan);
02824 
02825    newchan->_state = AST_STATE_UP;
02826    ast_clear_flag(newchan, AST_FLAGS_ALL);
02827    tobj = ast_calloc(1, sizeof(*tobj));
02828    if (!tobj) {
02829       ast_hangup(xferchan);
02830       ast_hangup(newchan);
02831       ast_party_connected_line_free(&connected_line);
02832       return -1;
02833    }
02834 
02835    tobj->chan = newchan;
02836    tobj->peer = xferchan;
02837    tobj->bconfig = *config;
02838 
02839    ast_channel_lock(newchan);
02840    features_datastore = ast_channel_datastore_find(newchan, &dial_features_info, NULL);
02841    if (features_datastore && (dialfeatures = features_datastore->data)) {
02842       ast_copy_flags(&tobj->bconfig.features_callee, &dialfeatures->my_features,
02843          AST_FLAGS_ALL);
02844    }
02845    ast_channel_unlock(newchan);
02846 
02847    ast_channel_lock(xferchan);
02848    features_datastore = ast_channel_datastore_find(xferchan, &dial_features_info, NULL);
02849    if (features_datastore && (dialfeatures = features_datastore->data)) {
02850       ast_copy_flags(&tobj->bconfig.features_caller, &dialfeatures->my_features,
02851          AST_FLAGS_ALL);
02852    }
02853    ast_channel_unlock(xferchan);
02854 
02855    if (tobj->bconfig.end_bridge_callback_data_fixup) {
02856       tobj->bconfig.end_bridge_callback_data_fixup(&tobj->bconfig, tobj->peer, tobj->chan);
02857    }
02858 
02859    /*
02860     * xferchan is transferee, and newchan is the transfer target
02861     * So...in a transfer, who is the caller and who is the callee?
02862     *
02863     * When the call is originally made, it is clear who is caller and callee.
02864     * When a transfer occurs, it is my humble opinion that the transferee becomes
02865     * the caller, and the transfer target is the callee.
02866     *
02867     * The problem is that these macros were set with the intention of the original
02868     * caller and callee taking those roles.  A transfer can totally mess things up,
02869     * to be technical.  What sucks even more is that you can't effectively change
02870     * the macros in the dialplan during the call from the transferer to the transfer
02871     * target because the transferee is stuck with whatever role he originally had.
02872     *
02873     * I think the answer here is just to make sure that it is well documented that
02874     * during a transfer, the transferee is the "caller" and the transfer target
02875     * is the "callee."
02876     *
02877     * This means that if party B calls party A, and party B transfers party A to
02878     * party C, then A has switched roles for the call.  Now party A will have the
02879     * caller macro called on his channel instead of the callee macro.
02880     *
02881     * Luckily, the method by which the party B to party C bridge is
02882     * launched above ensures that the transferee is the "chan" on
02883     * the bridge and the transfer target is the "peer," so my idea
02884     * for the roles post-transfer does not require extensive code
02885     * changes.
02886     */
02887 
02888    /* Transfer party C connected line to party A */
02889    ast_channel_lock(transferer);
02890    /*
02891     * Due to a limitation regarding when callerID is set on a Local channel,
02892     * we use the transferer's connected line information here.
02893     */
02894    ast_party_connected_line_copy(&connected_line, &transferer->connected);
02895    ast_channel_unlock(transferer);
02896    connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
02897    if (ast_channel_connected_line_macro(newchan, xferchan, &connected_line, 1, 0)) {
02898       ast_channel_update_connected_line(xferchan, &connected_line, NULL);
02899    }
02900 
02901    /* Transfer party A connected line to party C */
02902    ast_channel_lock(xferchan);
02903    ast_connected_line_copy_from_caller(&connected_line, &xferchan->caller);
02904    ast_channel_unlock(xferchan);
02905    connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
02906    if (ast_channel_connected_line_macro(xferchan, newchan, &connected_line, 0, 0)) {
02907       ast_channel_update_connected_line(newchan, &connected_line, NULL);
02908    }
02909 
02910    if (ast_stream_and_wait(newchan, xfersound, ""))
02911       ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
02912    bridge_call_thread_launch(tobj);
02913 
02914    ast_party_connected_line_free(&connected_line);
02915    return -1;/* The transferee is masqueraded and the original bridged channels can be hungup. */
02916 }
02917 
02918 /* add atxfer and automon as undefined so you can only use em if you configure them */
02919 #define FEATURES_COUNT ARRAY_LEN(builtin_features)
02920 
02921 AST_RWLOCK_DEFINE_STATIC(features_lock);
02922 
02923 static struct ast_call_feature builtin_features[] = {
02924    { AST_FEATURE_REDIRECT, "Blind Transfer", "blindxfer", "#", "#", builtin_blindtransfer, AST_FEATURE_FLAG_NEEDSDTMF, "" },
02925    { AST_FEATURE_REDIRECT, "Attended Transfer", "atxfer", "", "", builtin_atxfer, AST_FEATURE_FLAG_NEEDSDTMF, "" },
02926    { AST_FEATURE_AUTOMON, "One Touch Monitor", "automon", "", "", builtin_automonitor, AST_FEATURE_FLAG_NEEDSDTMF, "" },
02927    { AST_FEATURE_DISCONNECT, "Disconnect Call", "disconnect", "*", "*", builtin_disconnect, AST_FEATURE_FLAG_NEEDSDTMF, "" },
02928    { AST_FEATURE_PARKCALL, "Park Call", "parkcall", "", "", builtin_parkcall, AST_FEATURE_FLAG_NEEDSDTMF, "" },
02929    { AST_FEATURE_AUTOMIXMON, "One Touch MixMonitor", "automixmon", "", "", builtin_automixmonitor, AST_FEATURE_FLAG_NEEDSDTMF, "" },
02930 };
02931 
02932 
02933 static AST_RWLIST_HEAD_STATIC(feature_list, ast_call_feature);
02934 
02935 /*! \brief register new feature into feature_list*/
02936 void ast_register_feature(struct ast_call_feature *feature)
02937 {
02938    if (!feature) {
02939       ast_log(LOG_NOTICE,"You didn't pass a feature!\n");
02940       return;
02941    }
02942   
02943    AST_RWLIST_WRLOCK(&feature_list);
02944    AST_RWLIST_INSERT_HEAD(&feature_list,feature,feature_entry);
02945    AST_RWLIST_UNLOCK(&feature_list);
02946 
02947    ast_verb(2, "Registered Feature '%s'\n",feature->sname);
02948 }
02949 
02950 /*! 
02951  * \brief Add new feature group
02952  * \param fgname feature group name.
02953  *
02954  * Add new feature group to the feature group list insert at head of list.
02955  * \note This function MUST be called while feature_groups is locked.
02956  */
02957 static struct feature_group *register_group(const char *fgname)
02958 {
02959    struct feature_group *fg;
02960 
02961    if (!fgname) {
02962       ast_log(LOG_NOTICE, "You didn't pass a new group name!\n");
02963       return NULL;
02964    }
02965 
02966    if (!(fg = ast_calloc_with_stringfields(1, struct feature_group, 128))) {
02967       return NULL;
02968    }
02969 
02970    ast_string_field_set(fg, gname, fgname);
02971 
02972    AST_LIST_INSERT_HEAD(&feature_groups, fg, entry);
02973 
02974    ast_verb(2, "Registered group '%s'\n", fg->gname);
02975 
02976    return fg;
02977 }
02978 
02979 /*! 
02980  * \brief Add feature to group
02981  * \param fg feature group
02982  * \param exten
02983  * \param feature feature to add.
02984  *
02985  * Check fg and feature specified, add feature to list
02986  * \note This function MUST be called while feature_groups is locked. 
02987  */
02988 static void register_group_feature(struct feature_group *fg, const char *exten, struct ast_call_feature *feature)
02989 {
02990    struct feature_group_exten *fge;
02991 
02992    if (!fg) {
02993       ast_log(LOG_NOTICE, "You didn't pass a group!\n");
02994       return;
02995    }
02996 
02997    if (!feature) {
02998       ast_log(LOG_NOTICE, "You didn't pass a feature!\n");
02999       return;
03000    }
03001 
03002    if (!(fge = ast_calloc_with_stringfields(1, struct feature_group_exten, 128))) {
03003       return;
03004    }
03005 
03006    ast_string_field_set(fge, exten, S_OR(exten, feature->exten));
03007 
03008    fge->feature = feature;
03009 
03010    AST_LIST_INSERT_HEAD(&fg->features, fge, entry);
03011 
03012    ast_verb(2, "Registered feature '%s' for group '%s' at exten '%s'\n",
03013                feature->sname, fg->gname, fge->exten);
03014 }
03015 
03016 void ast_unregister_feature(struct ast_call_feature *feature)
03017 {
03018    if (!feature) {
03019       return;
03020    }
03021 
03022    AST_RWLIST_WRLOCK(&feature_list);
03023    AST_RWLIST_REMOVE(&feature_list, feature, feature_entry);
03024    AST_RWLIST_UNLOCK(&feature_list);
03025 
03026    ast_free(feature);
03027 }
03028 
03029 /*! \brief Remove all features in the list */
03030 static void ast_unregister_features(void)
03031 {
03032    struct ast_call_feature *feature;
03033 
03034    AST_RWLIST_WRLOCK(&feature_list);
03035    while ((feature = AST_RWLIST_REMOVE_HEAD(&feature_list, feature_entry))) {
03036       ast_free(feature);
03037    }
03038    AST_RWLIST_UNLOCK(&feature_list);
03039 }
03040 
03041 /*! \brief find a call feature by name */
03042 static struct ast_call_feature *find_dynamic_feature(const char *name)
03043 {
03044    struct ast_call_feature *tmp;
03045 
03046    AST_RWLIST_TRAVERSE(&feature_list, tmp, feature_entry) {
03047       if (!strcasecmp(tmp->sname, name)) {
03048          break;
03049       }
03050    }
03051 
03052    return tmp;
03053 }
03054 
03055 /*! \brief Remove all feature groups in the list */
03056 static void ast_unregister_groups(void)
03057 {
03058    struct feature_group *fg;
03059    struct feature_group_exten *fge;
03060 
03061    AST_RWLIST_WRLOCK(&feature_groups);
03062    while ((fg = AST_LIST_REMOVE_HEAD(&feature_groups, entry))) {
03063       while ((fge = AST_LIST_REMOVE_HEAD(&fg->features, entry))) {
03064          ast_string_field_free_memory(fge);
03065          ast_free(fge);
03066       }
03067 
03068       ast_string_field_free_memory(fg);
03069       ast_free(fg);
03070    }
03071    AST_RWLIST_UNLOCK(&feature_groups);
03072 }
03073 
03074 /*! 
03075  * \brief Find a group by name 
03076  * \param name feature name
03077  * \retval feature group on success.
03078  * \retval NULL on failure.
03079  */
03080 static struct feature_group *find_group(const char *name)
03081 {
03082    struct feature_group *fg = NULL;
03083 
03084    AST_LIST_TRAVERSE(&feature_groups, fg, entry) {
03085       if (!strcasecmp(fg->gname, name))
03086          break;
03087    }
03088 
03089    return fg;
03090 }
03091 
03092 void ast_rdlock_call_features(void)
03093 {
03094    ast_rwlock_rdlock(&features_lock);
03095 }
03096 
03097 void ast_unlock_call_features(void)
03098 {
03099    ast_rwlock_unlock(&features_lock);
03100 }
03101 
03102 struct ast_call_feature *ast_find_call_feature(const char *name)
03103 {
03104    int x;
03105    for (x = 0; x < FEATURES_COUNT; x++) {
03106       if (!strcasecmp(name, builtin_features[x].sname))
03107          return &builtin_features[x];
03108    }
03109    return NULL;
03110 }
03111 
03112 /*!
03113  * \brief exec an app by feature 
03114  * \param chan,peer,config,code,sense,data
03115  *
03116  * Find a feature, determine which channel activated
03117  * \retval AST_FEATURE_RETURN_NO_HANGUP_PEER
03118  * \retval -1 error.
03119  * \retval -2 when an application cannot be found.
03120  */
03121 static int feature_exec_app(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
03122 {
03123    struct ast_app *app;
03124    struct ast_call_feature *feature = data;
03125    struct ast_channel *work, *idle;
03126    int res;
03127 
03128    if (!feature) { /* shouldn't ever happen! */
03129       ast_log(LOG_NOTICE, "Found feature before, but at execing we've lost it??\n");
03130       return -1; 
03131    }
03132 
03133    if (sense == FEATURE_SENSE_CHAN) {
03134       if (!ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER))
03135          return AST_FEATURE_RETURN_KEEPTRYING;
03136       if (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF)) {
03137          work = chan;
03138          idle = peer;
03139       } else {
03140          work = peer;
03141          idle = chan;
03142       }
03143    } else {
03144       if (!ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE))
03145          return AST_FEATURE_RETURN_KEEPTRYING;
03146       if (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF)) {
03147          work = peer;
03148          idle = chan;
03149       } else {
03150          work = chan;
03151          idle = peer;
03152       }
03153    }
03154 
03155    if (!(app = pbx_findapp(feature->app))) {
03156       ast_log(LOG_WARNING, "Could not find application (%s)\n", feature->app);
03157       return -2;
03158    }
03159 
03160    ast_autoservice_start(idle);
03161    ast_autoservice_ignore(idle, AST_FRAME_DTMF_END);
03162    
03163    pbx_builtin_setvar_helper(work, "DYNAMIC_PEERNAME", idle->name);
03164    pbx_builtin_setvar_helper(idle, "DYNAMIC_PEERNAME", work->name);
03165    pbx_builtin_setvar_helper(work, "DYNAMIC_FEATURENAME", feature->sname);
03166    pbx_builtin_setvar_helper(idle, "DYNAMIC_FEATURENAME", feature->sname);
03167 
03168    if (!ast_strlen_zero(feature->moh_class))
03169       ast_moh_start(idle, feature->moh_class, NULL);
03170 
03171    res = pbx_exec(work, app, feature->app_args);
03172 
03173    if (!ast_strlen_zero(feature->moh_class))
03174       ast_moh_stop(idle);
03175 
03176    ast_autoservice_stop(idle);
03177 
03178    if (res) {
03179       return AST_FEATURE_RETURN_SUCCESSBREAK;
03180    }
03181    return AST_FEATURE_RETURN_SUCCESS;  /*! \todo XXX should probably return res */
03182 }
03183 
03184 static void unmap_features(void)
03185 {
03186    int x;
03187 
03188    ast_rwlock_wrlock(&features_lock);
03189    for (x = 0; x < FEATURES_COUNT; x++)
03190       strcpy(builtin_features[x].exten, builtin_features[x].default_exten);
03191    ast_rwlock_unlock(&features_lock);
03192 }
03193 
03194 static int remap_feature(const char *name, const char *value)
03195 {
03196    int x, res = -1;
03197 
03198    ast_rwlock_wrlock(&features_lock);
03199    for (x = 0; x < FEATURES_COUNT; x++) {
03200       if (strcasecmp(builtin_features[x].sname, name))
03201          continue;
03202 
03203       ast_copy_string(builtin_features[x].exten, value, sizeof(builtin_features[x].exten));
03204       res = 0;
03205       break;
03206    }
03207    ast_rwlock_unlock(&features_lock);
03208 
03209    return res;
03210 }
03211 
03212 /*!
03213  * \brief Helper function for feature_interpret and ast_feature_detect
03214  * \param chan,peer,config,code,sense,dynamic_features_buf,features,operation,feature
03215  *
03216  * Lock features list, browse for code, unlock list
03217  * If a feature is found and the operation variable is set, that feature's
03218  * operation is executed.  The first feature found is copied to the feature parameter.
03219  * \retval res on success.
03220  * \retval -1 on failure.
03221  */
03222 static int feature_interpret_helper(struct ast_channel *chan, struct ast_channel *peer,
03223    struct ast_bridge_config *config, const char *code, int sense, char *dynamic_features_buf,
03224    struct ast_flags *features, feature_interpret_op operation, struct ast_call_feature *feature)
03225 {
03226    int x;
03227    struct feature_group *fg = NULL;
03228    struct feature_group_exten *fge;
03229    struct ast_call_feature *tmpfeature;
03230    char *tmp, *tok;
03231    int res = AST_FEATURE_RETURN_PASSDIGITS;
03232    int feature_detected = 0;
03233 
03234    if (!(peer && chan && config) && operation == FEATURE_INTERPRET_DO) {
03235       return -1; /* can not run feature operation */
03236    }
03237 
03238    ast_rwlock_rdlock(&features_lock);
03239    for (x = 0; x < FEATURES_COUNT; x++) {
03240       if ((ast_test_flag(features, builtin_features[x].feature_mask)) &&
03241           !ast_strlen_zero(builtin_features[x].exten)) {
03242          /* Feature is up for consideration */
03243          if (!strcmp(builtin_features[x].exten, code)) {
03244             ast_debug(3, "Feature detected: fname=%s sname=%s exten=%s\n", builtin_features[x].fname, builtin_features[x].sname, builtin_features[x].exten);
03245             if (operation == FEATURE_INTERPRET_CHECK) {
03246                res = AST_FEATURE_RETURN_SUCCESS; /* We found something */
03247             } else if (operation == FEATURE_INTERPRET_DO) {
03248                res = builtin_features[x].operation(chan, peer, config, code, sense, NULL);
03249             }
03250             if (feature) {
03251                memcpy(feature, &builtin_features[x], sizeof(*feature));
03252             }
03253             feature_detected = 1;
03254             break;
03255          } else if (!strncmp(builtin_features[x].exten, code, strlen(code))) {
03256             if (res == AST_FEATURE_RETURN_PASSDIGITS) {
03257                res = AST_FEATURE_RETURN_STOREDIGITS;
03258             }
03259          }
03260       }
03261    }
03262    ast_rwlock_unlock(&features_lock);
03263 
03264    if (ast_strlen_zero(dynamic_features_buf) || feature_detected) {
03265       return res;
03266    }
03267 
03268    tmp = dynamic_features_buf;
03269 
03270    while ((tok = strsep(&tmp, "#"))) {
03271       AST_RWLIST_RDLOCK(&feature_groups);
03272 
03273       fg = find_group(tok);
03274 
03275       if (fg) {
03276          AST_LIST_TRAVERSE(&fg->features, fge, entry) {
03277             if (!strcmp(fge->exten, code)) {
03278                if (operation) {
03279                   res = fge->feature->operation(chan, peer, config, code, sense, fge->feature);
03280                }
03281                if (feature) {
03282                   memcpy(feature, fge->feature, sizeof(*feature));
03283                }
03284                if (res != AST_FEATURE_RETURN_KEEPTRYING) {
03285                   AST_RWLIST_UNLOCK(&feature_groups);
03286                   break;
03287                }
03288                res = AST_FEATURE_RETURN_PASSDIGITS;
03289             } else if (!strncmp(fge->exten, code, strlen(code))) {
03290                res = AST_FEATURE_RETURN_STOREDIGITS;
03291             }
03292          }
03293          if (fge) {
03294             break;
03295          }
03296       }
03297 
03298       AST_RWLIST_UNLOCK(&feature_groups);
03299 
03300       AST_RWLIST_RDLOCK(&feature_list);
03301 
03302       if (!(tmpfeature = find_dynamic_feature(tok))) {
03303          AST_RWLIST_UNLOCK(&feature_list);
03304          continue;
03305       }
03306 
03307       /* Feature is up for consideration */
03308       if (!strcmp(tmpfeature->exten, code)) {
03309          ast_verb(3, " Feature Found: %s exten: %s\n",tmpfeature->sname, tok);
03310          if (operation == FEATURE_INTERPRET_CHECK) {
03311             res = AST_FEATURE_RETURN_SUCCESS; /* We found something */
03312          } else if (operation == FEATURE_INTERPRET_DO) {
03313             res = tmpfeature->operation(chan, peer, config, code, sense, tmpfeature);
03314          }
03315          if (feature) {
03316             memcpy(feature, tmpfeature, sizeof(*feature));
03317          }
03318          if (res != AST_FEATURE_RETURN_KEEPTRYING) {
03319             AST_RWLIST_UNLOCK(&feature_list);
03320             break;
03321          }
03322          res = AST_FEATURE_RETURN_PASSDIGITS;
03323       } else if (!strncmp(tmpfeature->exten, code, strlen(code)))
03324          res = AST_FEATURE_RETURN_STOREDIGITS;
03325 
03326       AST_RWLIST_UNLOCK(&feature_list);
03327    }
03328 
03329    return res;
03330 }
03331 
03332 /*!
03333  * \brief Check the dynamic features
03334  * \param chan,peer,config,code,sense
03335  *
03336  * \retval res on success.
03337  * \retval -1 on failure.
03338  */
03339 static int feature_interpret(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense) {
03340 
03341    char dynamic_features_buf[128];
03342    const char *peer_dynamic_features, *chan_dynamic_features;
03343    struct ast_flags features;
03344    struct ast_call_feature feature;
03345    if (sense == FEATURE_SENSE_CHAN) {
03346       /* Coverity - This uninit_use should be ignored since this macro initializes the flags */
03347       ast_copy_flags(&features, &(config->features_caller), AST_FLAGS_ALL);
03348    }
03349    else {
03350       /* Coverity - This uninit_use should be ignored since this macro initializes the flags */
03351       ast_copy_flags(&features, &(config->features_callee), AST_FLAGS_ALL);
03352    }
03353 
03354    ast_channel_lock(peer);
03355    peer_dynamic_features = ast_strdupa(S_OR(pbx_builtin_getvar_helper(peer, "DYNAMIC_FEATURES"),""));
03356    ast_channel_unlock(peer);
03357 
03358    ast_channel_lock(chan);
03359    chan_dynamic_features = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES"),""));
03360    ast_channel_unlock(chan);
03361 
03362    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,""));
03363 
03364    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);
03365 
03366    return feature_interpret_helper(chan, peer, config, code, sense, dynamic_features_buf, &features, FEATURE_INTERPRET_DO, &feature);
03367 }
03368 
03369 
03370 int ast_feature_detect(struct ast_channel *chan, struct ast_flags *features, const char *code, struct ast_call_feature *feature) {
03371 
03372    return feature_interpret_helper(chan, NULL, NULL, code, 0, NULL, features, FEATURE_INTERPRET_DETECT, feature);
03373 }
03374 
03375 /*! \brief Check if a feature exists */
03376 static int feature_check(struct ast_channel *chan, struct ast_flags *features, char *code) {
03377    char *chan_dynamic_features;
03378    ast_channel_lock(chan);
03379    chan_dynamic_features = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES"),""));
03380    ast_channel_unlock(chan);
03381 
03382    return feature_interpret_helper(chan, NULL, NULL, code, 0, chan_dynamic_features, features, FEATURE_INTERPRET_CHECK, NULL);
03383 }
03384 
03385 static void set_config_flags(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config)
03386 {
03387    int x;
03388 
03389    ast_clear_flag(config, AST_FLAGS_ALL);
03390 
03391    ast_rwlock_rdlock(&features_lock);
03392    for (x = 0; x < FEATURES_COUNT; x++) {
03393       if (!ast_test_flag(builtin_features + x, AST_FEATURE_FLAG_NEEDSDTMF))
03394          continue;
03395 
03396       if (ast_test_flag(&(config->features_caller), builtin_features[x].feature_mask))
03397          ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
03398 
03399       if (ast_test_flag(&(config->features_callee), builtin_features[x].feature_mask))
03400          ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
03401    }
03402    ast_rwlock_unlock(&features_lock);
03403 
03404    if (chan && peer && !(ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_0) && ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_1))) {
03405       const char *dynamic_features = pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES");
03406 
03407       if (dynamic_features) {
03408          char *tmp = ast_strdupa(dynamic_features);
03409          char *tok;
03410          struct ast_call_feature *feature;
03411 
03412          /* while we have a feature */
03413          while ((tok = strsep(&tmp, "#"))) {
03414             struct feature_group *fg;
03415 
03416             AST_RWLIST_RDLOCK(&feature_groups);
03417             AST_RWLIST_TRAVERSE(&feature_groups, fg, entry) {
03418                struct feature_group_exten *fge;
03419 
03420                AST_LIST_TRAVERSE(&fg->features, fge, entry) {
03421                   if (ast_test_flag(fge->feature, AST_FEATURE_FLAG_BYCALLER)) {
03422                      ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
03423                   }
03424                   if (ast_test_flag(fge->feature, AST_FEATURE_FLAG_BYCALLEE)) {
03425                      ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
03426                   }
03427                }
03428             }
03429             AST_RWLIST_UNLOCK(&feature_groups);
03430 
03431             AST_RWLIST_RDLOCK(&feature_list);
03432             if ((feature = find_dynamic_feature(tok)) && ast_test_flag(feature, AST_FEATURE_FLAG_NEEDSDTMF)) {
03433                if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER)) {
03434                   ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
03435                }
03436                if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE)) {
03437                   ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
03438                }
03439             }
03440             AST_RWLIST_UNLOCK(&feature_list);
03441          }
03442       }
03443    }
03444 }
03445 
03446 /*!
03447  * \internal
03448  * \brief Get feature and dial.
03449  *
03450  * \param caller Channel to represent as the calling channel for the dialed channel.
03451  * \param caller_name Original caller channel name.
03452  * \param requestor Channel to say is requesting the dial (usually the caller).
03453  * \param transferee Channel that the dialed channel will be transferred to.
03454  * \param type Channel technology type to dial.
03455  * \param format Codec formats for dialed channel.
03456  * \param data Dialed channel extra parameters for ast_request() and ast_call().
03457  * \param timeout Time limit for dialed channel to answer in ms. Must be greater than zero.
03458  * \param outstate Status of dialed channel if unsuccessful.
03459  * \param language Language of the caller.
03460  *
03461  * \note
03462  * outstate can be:
03463  * 0, AST_CONTROL_BUSY, AST_CONTROL_CONGESTION,
03464  * AST_CONTROL_ANSWER, or AST_CONTROL_UNHOLD.  If
03465  * AST_CONTROL_UNHOLD then the caller channel cancelled the
03466  * transfer or the dialed channel did not answer before the
03467  * timeout.
03468  *
03469  * \details
03470  * Request channel, set channel variables, initiate call,
03471  * check if they want to disconnect, go into loop, check if timeout has elapsed,
03472  * check if person to be transfered hung up, check for answer break loop,
03473  * set cdr return channel.
03474  *
03475  * \retval Channel Connected channel for transfer.
03476  * \retval NULL on failure to get third party connected.
03477  *
03478  * \note This is similar to __ast_request_and_dial() in channel.c
03479  */
03480 static struct ast_channel *feature_request_and_dial(struct ast_channel *caller,
03481    const char *caller_name, struct ast_channel *requestor,
03482    struct ast_channel *transferee, const char *type, format_t format, void *data,
03483    int timeout, int *outstate, const char *language)
03484 {
03485    int state = 0;
03486    int cause = 0;
03487    int to;
03488    int caller_hungup;
03489    int transferee_hungup;
03490    struct ast_channel *chan;
03491    struct ast_channel *monitor_chans[3];
03492    struct ast_channel *active_channel;
03493    int res;
03494    int ready = 0;
03495    struct timeval started;
03496    int x, len = 0;
03497    char *disconnect_code = NULL, *dialed_code = NULL;
03498    struct ast_frame *f;
03499    AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
03500 
03501    caller_hungup = ast_check_hangup(caller);
03502 
03503    if (!(chan = ast_request(type, format, requestor, data, &cause))) {
03504       ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
03505       switch (cause) {
03506       case AST_CAUSE_BUSY:
03507          state = AST_CONTROL_BUSY;
03508          break;
03509       case AST_CAUSE_CONGESTION:
03510          state = AST_CONTROL_CONGESTION;
03511          break;
03512       default:
03513          state = 0;
03514          break;
03515       }
03516       goto done;
03517    }
03518 
03519    ast_string_field_set(chan, language, language);
03520    ast_channel_inherit_variables(caller, chan);
03521    pbx_builtin_setvar_helper(chan, "TRANSFERERNAME", caller_name);
03522 
03523    ast_channel_lock(chan);
03524    ast_connected_line_copy_from_caller(&chan->connected, &requestor->caller);
03525    ast_channel_unlock(chan);
03526 
03527    if (ast_call(chan, data, timeout)) {
03528       ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
03529       switch (chan->hangupcause) {
03530       case AST_CAUSE_BUSY:
03531          state = AST_CONTROL_BUSY;
03532          break;
03533       case AST_CAUSE_CONGESTION:
03534          state = AST_CONTROL_CONGESTION;
03535          break;
03536       default:
03537          state = 0;
03538          break;
03539       }
03540       goto done;
03541    }
03542 
03543    /* support dialing of the featuremap disconnect code while performing an attended tranfer */
03544    ast_rwlock_rdlock(&features_lock);
03545    for (x = 0; x < FEATURES_COUNT; x++) {
03546       if (strcasecmp(builtin_features[x].sname, "disconnect"))
03547          continue;
03548 
03549       disconnect_code = builtin_features[x].exten;
03550       len = strlen(disconnect_code) + 1;
03551       dialed_code = alloca(len);
03552       memset(dialed_code, 0, len);
03553       break;
03554    }
03555    ast_rwlock_unlock(&features_lock);
03556    x = 0;
03557    started = ast_tvnow();
03558    to = timeout;
03559    AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
03560 
03561    ast_poll_channel_add(caller, chan);
03562 
03563    transferee_hungup = 0;
03564    while (!ast_check_hangup(transferee) && (chan->_state != AST_STATE_UP)) {
03565       int num_chans = 0;
03566 
03567       monitor_chans[num_chans++] = transferee;
03568       monitor_chans[num_chans++] = chan;
03569       if (!caller_hungup) {
03570          if (ast_check_hangup(caller)) {
03571             caller_hungup = 1;
03572 
03573 #if defined(ATXFER_NULL_TECH)
03574             /* Change caller's name to ensure that it will remain unique. */
03575             set_new_chan_name(caller);
03576 
03577             /*
03578              * Get rid of caller's physical technology so it is free for
03579              * other calls.
03580              */
03581             set_kill_chan_tech(caller);
03582 #endif   /* defined(ATXFER_NULL_TECH) */
03583          } else {
03584             /* caller is not hungup so monitor it. */
03585             monitor_chans[num_chans++] = caller;
03586          }
03587       }
03588 
03589       /* see if the timeout has been violated */
03590       if (ast_tvdiff_ms(ast_tvnow(), started) > timeout) {
03591          state = AST_CONTROL_UNHOLD;
03592          ast_log(LOG_NOTICE, "We exceeded our AT-timeout for %s\n", chan->name);
03593          break; /*doh! timeout*/
03594       }
03595 
03596       active_channel = ast_waitfor_n(monitor_chans, num_chans, &to);
03597       if (!active_channel)
03598          continue;
03599 
03600       f = NULL;
03601       if (transferee == active_channel) {
03602          struct ast_frame *dup_f;
03603 
03604          f = ast_read(transferee);
03605          if (f == NULL) { /*doh! where'd he go?*/
03606             transferee_hungup = 1;
03607             state = 0;
03608             break;
03609          }
03610          if (ast_is_deferrable_frame(f)) {
03611             dup_f = ast_frisolate(f);
03612             if (dup_f) {
03613                if (dup_f == f) {
03614                   f = NULL;
03615                }
03616                AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
03617             }
03618          }
03619       } else if (chan == active_channel) {
03620          if (!ast_strlen_zero(chan->call_forward)) {
03621             state = 0;
03622             ast_autoservice_start(transferee);
03623             chan = ast_call_forward(caller, chan, NULL, format, NULL, &state);
03624             ast_autoservice_stop(transferee);
03625             if (!chan) {
03626                break;
03627             }
03628             continue;
03629          }
03630          f = ast_read(chan);
03631          if (f == NULL) { /*doh! where'd he go?*/
03632             switch (chan->hangupcause) {
03633             case AST_CAUSE_BUSY:
03634                state = AST_CONTROL_BUSY;
03635                break;
03636             case AST_CAUSE_CONGESTION:
03637                state = AST_CONTROL_CONGESTION;
03638                break;
03639             default:
03640                state = 0;
03641                break;
03642             }
03643             break;
03644          }
03645 
03646          if (f->frametype == AST_FRAME_CONTROL) {
03647             if (f->subclass.integer == AST_CONTROL_RINGING) {
03648                ast_verb(3, "%s is ringing\n", chan->name);
03649                ast_indicate(caller, AST_CONTROL_RINGING);
03650             } else if (f->subclass.integer == AST_CONTROL_BUSY) {
03651                state = f->subclass.integer;
03652                ast_verb(3, "%s is busy\n", chan->name);
03653                ast_indicate(caller, AST_CONTROL_BUSY);
03654                ast_frfree(f);
03655                break;
03656             } else if (f->subclass.integer == AST_CONTROL_INCOMPLETE) {
03657                ast_verb(3, "%s dialed incomplete extension %s; ignoring\n", chan->name, chan->exten);
03658             } else if (f->subclass.integer == AST_CONTROL_CONGESTION) {
03659                state = f->subclass.integer;
03660                ast_verb(3, "%s is congested\n", chan->name);
03661                ast_indicate(caller, AST_CONTROL_CONGESTION);
03662                ast_frfree(f);
03663                break;
03664             } else if (f->subclass.integer == AST_CONTROL_ANSWER) {
03665                /* This is what we are hoping for */
03666                state = f->subclass.integer;
03667                ast_frfree(f);
03668                ready=1;
03669                break;
03670             } else if (f->subclass.integer == AST_CONTROL_CONNECTED_LINE) {
03671                if (caller_hungup) {
03672                   struct ast_party_connected_line connected;
03673 
03674                   /* Just save it for the transfer. */
03675                   ast_party_connected_line_set_init(&connected, &caller->connected);
03676                   res = ast_connected_line_parse_data(f->data.ptr, f->datalen,
03677                      &connected);
03678                   if (!res) {
03679                      ast_channel_set_connected_line(caller, &connected, NULL);
03680                   }
03681                   ast_party_connected_line_free(&connected);
03682                } else {
03683                   ast_autoservice_start(transferee);
03684                   if (ast_channel_connected_line_macro(chan, caller, f, 1, 1)) {
03685                      ast_indicate_data(caller, AST_CONTROL_CONNECTED_LINE,
03686                         f->data.ptr, f->datalen);
03687                   }
03688                   ast_autoservice_stop(transferee);
03689                }
03690             } else if (f->subclass.integer == AST_CONTROL_REDIRECTING) {
03691                if (!caller_hungup) {
03692                   ast_autoservice_start(transferee);
03693                   if (ast_channel_redirecting_macro(chan, caller, f, 1, 1)) {
03694                      ast_indicate_data(caller, AST_CONTROL_REDIRECTING,
03695                         f->data.ptr, f->datalen);
03696                   }
03697                   ast_autoservice_stop(transferee);
03698                }
03699             } else if (f->subclass.integer != -1
03700                && f->subclass.integer != AST_CONTROL_PROGRESS
03701                && f->subclass.integer != AST_CONTROL_PROCEEDING) {
03702                ast_log(LOG_NOTICE, "Don't know what to do about control frame: %d\n", f->subclass.integer);
03703             }
03704             /* else who cares */
03705          } else if (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO) {
03706             ast_write(caller, f);
03707          }
03708       } else if (caller == active_channel) {
03709          f = ast_read(caller);
03710          if (f) {
03711             if (f->frametype == AST_FRAME_DTMF) {
03712                dialed_code[x++] = f->subclass.integer;
03713                dialed_code[x] = '\0';
03714                if (strlen(dialed_code) == len) {
03715                   x = 0;
03716                } else if (x && strncmp(dialed_code, disconnect_code, x)) {
03717                   x = 0;
03718                   dialed_code[x] = '\0';
03719                }
03720                if (*dialed_code && !strcmp(dialed_code, disconnect_code)) {
03721                   /* Caller Canceled the call */
03722                   state = AST_CONTROL_UNHOLD;
03723                   ast_frfree(f);
03724                   break;
03725                }
03726             } else if (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO) {
03727                ast_write(chan, f);
03728             }
03729          }
03730       }
03731       if (f)
03732          ast_frfree(f);
03733    } /* end while */
03734 
03735    ast_poll_channel_del(caller, chan);
03736 
03737    /*
03738     * We need to free all the deferred frames, but we only need to
03739     * queue the deferred frames if no hangup was received.
03740     */
03741    ast_channel_lock(transferee);
03742    transferee_hungup = (transferee_hungup || ast_check_hangup(transferee));
03743    while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
03744       if (!transferee_hungup) {
03745          ast_queue_frame_head(transferee, f);
03746       }
03747       ast_frfree(f);
03748    }
03749    ast_channel_unlock(transferee);
03750 
03751 done:
03752    ast_indicate(caller, -1);
03753    if (chan && (ready || chan->_state == AST_STATE_UP)) {
03754       state = AST_CONTROL_ANSWER;
03755    } else if (chan) {
03756       ast_hangup(chan);
03757       chan = NULL;
03758    }
03759 
03760    if (outstate)
03761       *outstate = state;
03762 
03763    return chan;
03764 }
03765 
03766 void ast_channel_log(char *title, struct ast_channel *chan);
03767 
03768 void ast_channel_log(char *title, struct ast_channel *chan) /* for debug, this is handy enough to justify keeping it in the source */
03769 {
03770        ast_log(LOG_NOTICE, "______ %s (%lx)______\n", title, (unsigned long)chan);
03771        ast_log(LOG_NOTICE, "CHAN: name: %s;  appl: %s; data: %s; contxt: %s;  exten: %s; pri: %d;\n",
03772                        chan->name, chan->appl, chan->data, chan->context, chan->exten, chan->priority);
03773        ast_log(LOG_NOTICE, "CHAN: acctcode: %s;  dialcontext: %s; amaflags: %x; maccontxt: %s;  macexten: %s; macpri: %d;\n",
03774                        chan->accountcode, chan->dialcontext, chan->amaflags, chan->macrocontext, chan->macroexten, chan->macropriority);
03775        ast_log(LOG_NOTICE, "CHAN: masq: %p;  masqr: %p; _bridge: %p; uniqueID: %s; linkedID:%s\n",
03776                        chan->masq, chan->masqr,
03777                        chan->_bridge, chan->uniqueid, chan->linkedid);
03778        if (chan->masqr)
03779                ast_log(LOG_NOTICE, "CHAN: masquerading as: %s;  cdr: %p;\n",
03780                                chan->masqr->name, chan->masqr->cdr);
03781        if (chan->_bridge)
03782                ast_log(LOG_NOTICE, "CHAN: Bridged to %s\n", chan->_bridge->name);
03783 
03784    ast_log(LOG_NOTICE, "===== done ====\n");
03785 }
03786 
03787 /*!
03788  * \brief return the first unlocked cdr in a possible chain
03789  */
03790 static struct ast_cdr *pick_unlocked_cdr(struct ast_cdr *cdr)
03791 {
03792    struct ast_cdr *cdr_orig = cdr;
03793    while (cdr) {
03794       if (!ast_test_flag(cdr,AST_CDR_FLAG_LOCKED))
03795          return cdr;
03796       cdr = cdr->next;
03797    }
03798    return cdr_orig; /* everybody LOCKED or some other weirdness, like a NULL */
03799 }
03800 
03801 static void set_bridge_features_on_config(struct ast_bridge_config *config, const char *features)
03802 {
03803    const char *feature;
03804 
03805    if (ast_strlen_zero(features)) {
03806       return;
03807    }
03808 
03809    for (feature = features; *feature; feature++) {
03810       switch (*feature) {
03811       case 'T' :
03812       case 't' :
03813          ast_set_flag(&(config->features_caller), AST_FEATURE_REDIRECT);
03814          break;
03815       case 'K' :
03816       case 'k' :
03817          ast_set_flag(&(config->features_caller), AST_FEATURE_PARKCALL);
03818          break;
03819       case 'H' :
03820       case 'h' :
03821          ast_set_flag(&(config->features_caller), AST_FEATURE_DISCONNECT);
03822          break;
03823       case 'W' :
03824       case 'w' :
03825          ast_set_flag(&(config->features_caller), AST_FEATURE_AUTOMON);
03826          break;
03827       default :
03828          ast_log(LOG_WARNING, "Skipping unknown feature code '%c'\n", *feature);
03829       }
03830    }
03831 }
03832 
03833 static void add_features_datastores(struct ast_channel *caller, struct ast_channel *callee, struct ast_bridge_config *config)
03834 {
03835    if (add_features_datastore(caller, &config->features_caller, &config->features_callee)) {
03836       /*
03837        * If we don't return here, then when we do a builtin_atxfer we
03838        * will copy the disconnect flags over from the atxfer to the
03839        * callee (Party C).
03840        */
03841       return;
03842    }
03843 
03844    add_features_datastore(callee, &config->features_callee, &config->features_caller);
03845 }
03846 
03847 static void clear_dialed_interfaces(struct ast_channel *chan)
03848 {
03849    struct ast_datastore *di_datastore;
03850 
03851    ast_channel_lock(chan);
03852    if ((di_datastore = ast_channel_datastore_find(chan, &dialed_interface_info, NULL))) {
03853       if (option_debug) {
03854          ast_log(LOG_DEBUG, "Removing dialed interfaces datastore on %s since we're bridging\n", chan->name);
03855       }
03856       if (!ast_channel_datastore_remove(chan, di_datastore)) {
03857          ast_datastore_free(di_datastore);
03858       }
03859    }
03860    ast_channel_unlock(chan);
03861 }
03862 
03863 /*!
03864  * \brief bridge the call and set CDR
03865  *
03866  * \param chan The bridge considers this channel the caller.
03867  * \param peer The bridge considers this channel the callee.
03868  * \param config Configuration for this bridge.
03869  *
03870  * Set start time, check for two channels,check if monitor on
03871  * check for feature activation, create new CDR
03872  * \retval res on success.
03873  * \retval -1 on failure to bridge.
03874  */
03875 int ast_bridge_call(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config)
03876 {
03877    /* Copy voice back and forth between the two channels.  Give the peer
03878       the ability to transfer calls with '#<extension' syntax. */
03879    struct ast_frame *f;
03880    struct ast_channel *who;
03881    char chan_featurecode[FEATURE_MAX_LEN + 1]="";
03882    char peer_featurecode[FEATURE_MAX_LEN + 1]="";
03883    char orig_channame[AST_CHANNEL_NAME];
03884    char orig_peername[AST_CHANNEL_NAME];
03885    int res;
03886    int diff;
03887    int hasfeatures=0;
03888    int hadfeatures=0;
03889    int autoloopflag;
03890    int sendingdtmfdigit = 0;
03891    int we_disabled_peer_cdr = 0;
03892    struct ast_option_header *aoh;
03893    struct ast_cdr *bridge_cdr = NULL;
03894    struct ast_cdr *chan_cdr = chan->cdr; /* the proper chan cdr, if there are forked cdrs */
03895    struct ast_cdr *peer_cdr = peer->cdr; /* the proper chan cdr, if there are forked cdrs */
03896    struct ast_cdr *new_chan_cdr = NULL; /* the proper chan cdr, if there are forked cdrs */
03897    struct ast_cdr *new_peer_cdr = NULL; /* the proper chan cdr, if there are forked cdrs */
03898    struct ast_silence_generator *silgen = NULL;
03899    const char *h_context;
03900 
03901    pbx_builtin_setvar_helper(chan, "BRIDGEPEER", peer->name);
03902    pbx_builtin_setvar_helper(peer, "BRIDGEPEER", chan->name);
03903 
03904    /* Clear any BLINDTRANSFER since the transfer has completed. */
03905    pbx_builtin_setvar_helper(chan, "BLINDTRANSFER", NULL);
03906    pbx_builtin_setvar_helper(peer, "BLINDTRANSFER", NULL);
03907 
03908    set_bridge_features_on_config(config, pbx_builtin_getvar_helper(chan, "BRIDGE_FEATURES"));
03909    add_features_datastores(chan, peer, config);
03910 
03911    /* This is an interesting case.  One example is if a ringing channel gets redirected to
03912     * an extension that picks up a parked call.  This will make sure that the call taken
03913     * out of parking gets told that the channel it just got bridged to is still ringing. */
03914    if (chan->_state == AST_STATE_RINGING && peer->visible_indication != AST_CONTROL_RINGING) {
03915       ast_indicate(peer, AST_CONTROL_RINGING);
03916    }
03917 
03918    if (monitor_ok) {
03919       const char *monitor_exec;
03920       struct ast_channel *src = NULL;
03921       if (!monitor_app) {
03922          if (!(monitor_app = pbx_findapp("Monitor")))
03923             monitor_ok=0;
03924       }
03925       if ((monitor_exec = pbx_builtin_getvar_helper(chan, "AUTO_MONITOR"))) 
03926          src = chan;
03927       else if ((monitor_exec = pbx_builtin_getvar_helper(peer, "AUTO_MONITOR")))
03928          src = peer;
03929       if (monitor_app && src) {
03930          char *tmp = ast_strdupa(monitor_exec);
03931          pbx_exec(src, monitor_app, tmp);
03932       }
03933    }
03934 
03935    set_config_flags(chan, peer, config);
03936 
03937    /* Answer if need be */
03938    if (chan->_state != AST_STATE_UP) {
03939       if (ast_raw_answer(chan, 1)) {
03940          return -1;
03941       }
03942    }
03943 
03944 #ifdef FOR_DEBUG
03945    /* show the two channels and cdrs involved in the bridge for debug & devel purposes */
03946    ast_channel_log("Pre-bridge CHAN Channel info", chan);
03947    ast_channel_log("Pre-bridge PEER Channel info", peer);
03948 #endif
03949    /* two channels are being marked as linked here */
03950    ast_channel_set_linkgroup(chan,peer);
03951 
03952    /* copy the userfield from the B-leg to A-leg if applicable */
03953    if (chan->cdr && peer->cdr && !ast_strlen_zero(peer->cdr->userfield)) {
03954       char tmp[256];
03955 
03956       ast_channel_lock(chan);
03957       if (!ast_strlen_zero(chan->cdr->userfield)) {
03958          snprintf(tmp, sizeof(tmp), "%s;%s", chan->cdr->userfield, peer->cdr->userfield);
03959          ast_cdr_appenduserfield(chan, tmp);
03960       } else {
03961          ast_cdr_setuserfield(chan, peer->cdr->userfield);
03962       }
03963       ast_channel_unlock(chan);
03964       /* Don't delete the CDR; just disable it. */
03965       ast_set_flag(peer->cdr, AST_CDR_FLAG_POST_DISABLED);
03966       we_disabled_peer_cdr = 1;
03967    }
03968    ast_copy_string(orig_channame,chan->name,sizeof(orig_channame));
03969    ast_copy_string(orig_peername,peer->name,sizeof(orig_peername));
03970 
03971    if (!chan_cdr || (chan_cdr && !ast_test_flag(chan_cdr, AST_CDR_FLAG_POST_DISABLED))) {
03972       ast_channel_lock_both(chan, peer);
03973       if (chan_cdr) {
03974          ast_set_flag(chan_cdr, AST_CDR_FLAG_MAIN);
03975          ast_cdr_update(chan);
03976          bridge_cdr = ast_cdr_dup_unique_swap(chan_cdr);
03977          /* rip any forked CDR's off of the chan_cdr and attach
03978           * them to the bridge_cdr instead */
03979          bridge_cdr->next = chan_cdr->next;
03980          chan_cdr->next = NULL;
03981          ast_copy_string(bridge_cdr->lastapp, S_OR(chan->appl, ""), sizeof(bridge_cdr->lastapp));
03982          ast_copy_string(bridge_cdr->lastdata, S_OR(chan->data, ""), sizeof(bridge_cdr->lastdata));
03983          if (peer_cdr && !ast_strlen_zero(peer_cdr->userfield)) {
03984             ast_copy_string(bridge_cdr->userfield, peer_cdr->userfield, sizeof(bridge_cdr->userfield));
03985          }
03986          ast_cdr_setaccount(peer, chan->accountcode);
03987       } else {
03988          /* better yet, in a xfer situation, find out why the chan cdr got zapped (pun unintentional) */
03989          bridge_cdr = ast_cdr_alloc(); /* this should be really, really rare/impossible? */
03990          ast_copy_string(bridge_cdr->channel, chan->name, sizeof(bridge_cdr->channel));
03991          ast_copy_string(bridge_cdr->dstchannel, peer->name, sizeof(bridge_cdr->dstchannel));
03992          ast_copy_string(bridge_cdr->uniqueid, chan->uniqueid, sizeof(bridge_cdr->uniqueid));
03993          ast_copy_string(bridge_cdr->lastapp, S_OR(chan->appl, ""), sizeof(bridge_cdr->lastapp));
03994          ast_copy_string(bridge_cdr->lastdata, S_OR(chan->data, ""), sizeof(bridge_cdr->lastdata));
03995          ast_cdr_setcid(bridge_cdr, chan);
03996          bridge_cdr->disposition = (chan->_state == AST_STATE_UP) ?  AST_CDR_ANSWERED : AST_CDR_NULL;
03997          bridge_cdr->amaflags = chan->amaflags ? chan->amaflags :  ast_default_amaflags;
03998          ast_copy_string(bridge_cdr->accountcode, chan->accountcode, sizeof(bridge_cdr->accountcode));
03999          /* Destination information */
04000          ast_copy_string(bridge_cdr->dst, chan->exten, sizeof(bridge_cdr->dst));
04001          ast_copy_string(bridge_cdr->dcontext, chan->context, sizeof(bridge_cdr->dcontext));
04002          if (peer_cdr) {
04003             bridge_cdr->start = peer_cdr->start;
04004             ast_copy_string(bridge_cdr->userfield, peer_cdr->userfield, sizeof(bridge_cdr->userfield));
04005          } else {
04006             ast_cdr_start(bridge_cdr);
04007          }
04008       }
04009       ast_channel_unlock(chan);
04010       ast_channel_unlock(peer);
04011 
04012       ast_debug(4,"bridge answer set, chan answer set\n");
04013       /* peer_cdr->answer will be set when a macro runs on the peer;
04014          in that case, the bridge answer will be delayed while the
04015          macro plays on the peer channel. The peer answered the call
04016          before the macro started playing. To the phone system,
04017          this is billable time for the call, even tho the caller
04018          hears nothing but ringing while the macro does its thing. */
04019 
04020       /* Another case where the peer cdr's time will be set, is when
04021          A self-parks by pickup up phone and dialing 700, then B
04022          picks up A by dialing its parking slot; there may be more 
04023          practical paths that get the same result, tho... in which
04024          case you get the previous answer time from the Park... which
04025          is before the bridge's start time, so I added in the 
04026          tvcmp check to the if below */
04027 
04028       if (peer_cdr && !ast_tvzero(peer_cdr->answer) && ast_tvcmp(peer_cdr->answer, bridge_cdr->start) >= 0) {
04029          ast_cdr_setanswer(bridge_cdr, peer_cdr->answer);
04030          ast_cdr_setdisposition(bridge_cdr, peer_cdr->disposition);
04031          if (chan_cdr) {
04032             ast_cdr_setanswer(chan_cdr, peer_cdr->answer);
04033             ast_cdr_setdisposition(chan_cdr, peer_cdr->disposition);
04034          }
04035       } else {
04036          ast_cdr_answer(bridge_cdr);
04037          if (chan_cdr) {
04038             ast_cdr_answer(chan_cdr); /* for the sake of cli status checks */
04039          }
04040       }
04041       if (ast_test_flag(chan,AST_FLAG_BRIDGE_HANGUP_DONT) && (chan_cdr || peer_cdr)) {
04042          if (chan_cdr) {
04043             ast_set_flag(chan_cdr, AST_CDR_FLAG_BRIDGED);
04044          }
04045          if (peer_cdr) {
04046             ast_set_flag(peer_cdr, AST_CDR_FLAG_BRIDGED);
04047          }
04048       }
04049       /* the DIALED flag may be set if a dialed channel is transfered
04050        * and then bridged to another channel.  In order for the
04051        * bridge CDR to be written, the DIALED flag must not be
04052        * present. */
04053       ast_clear_flag(bridge_cdr, AST_CDR_FLAG_DIALED);
04054    }
04055    ast_cel_report_event(chan, AST_CEL_BRIDGE_START, NULL, NULL, peer);
04056 
04057    /* If we are bridging a call, stop worrying about forwarding loops. We presume that if
04058     * a call is being bridged, that the humans in charge know what they're doing. If they
04059     * don't, well, what can we do about that? */
04060    clear_dialed_interfaces(chan);
04061    clear_dialed_interfaces(peer);
04062 
04063    for (;;) {
04064       struct ast_channel *other; /* used later */
04065    
04066       res = ast_channel_bridge(chan, peer, config, &f, &who);
04067 
04068       if (ast_test_flag(chan, AST_FLAG_ZOMBIE)
04069          || ast_test_flag(peer, AST_FLAG_ZOMBIE)) {
04070          /* Zombies are present time to leave! */
04071          res = -1;
04072          if (f) {
04073             ast_frfree(f);
04074          }
04075          goto before_you_go;
04076       }
04077 
04078       /* When frame is not set, we are probably involved in a situation
04079          where we've timed out.
04080          When frame is set, we'll come this code twice; once for DTMF_BEGIN
04081          and also for DTMF_END. If we flow into the following 'if' for both, then 
04082          our wait times are cut in half, as both will subtract from the
04083          feature_timer. Not good!
04084       */
04085       if (config->feature_timer && (!f || f->frametype == AST_FRAME_DTMF_END)) {
04086          /* Update feature timer for next pass */
04087          diff = ast_tvdiff_ms(ast_tvnow(), config->feature_start_time);
04088          if (res == AST_BRIDGE_RETRY) {
04089             /* The feature fully timed out but has not been updated. Skip
04090              * the potential round error from the diff calculation and
04091              * explicitly set to expired. */
04092             config->feature_timer = -1;
04093          } else {
04094             config->feature_timer -= diff;
04095          }
04096 
04097          if (hasfeatures) {
04098             if (config->feature_timer <= 0) {
04099                /* Not *really* out of time, just out of time for
04100                   digits to come in for features. */
04101                ast_debug(1, "Timed out for feature!\n");
04102                if (!ast_strlen_zero(peer_featurecode)) {
04103                   ast_dtmf_stream(chan, peer, peer_featurecode, 0, 0);
04104                   memset(peer_featurecode, 0, sizeof(peer_featurecode));
04105                }
04106                if (!ast_strlen_zero(chan_featurecode)) {
04107                   ast_dtmf_stream(peer, chan, chan_featurecode, 0, 0);
04108                   memset(chan_featurecode, 0, sizeof(chan_featurecode));
04109                }
04110                if (f)
04111                   ast_frfree(f);
04112                hasfeatures = !ast_strlen_zero(chan_featurecode) || !ast_strlen_zero(peer_featurecode);
04113                if (!hasfeatures) {
04114                   /* No more digits expected - reset the timer */
04115                   config->feature_timer = 0;
04116                }
04117                hadfeatures = hasfeatures;
04118                /* Continue as we were */
04119                continue;
04120             } else if (!f) {
04121                /* The bridge returned without a frame and there is a feature in progress.
04122                 * However, we don't think the feature has quite yet timed out, so just
04123                 * go back into the bridge. */
04124                continue;
04125             }
04126          } else {
04127             if (config->feature_timer <=0) {
04128                /* We ran out of time */
04129                config->feature_timer = 0;
04130                who = chan;
04131                if (f)
04132                   ast_frfree(f);
04133                f = NULL;
04134                res = 0;
04135             }
04136          }
04137       }
04138       if (res < 0) {
04139          if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_test_flag(peer, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan) && !ast_check_hangup(peer)) {
04140             ast_log(LOG_WARNING, "Bridge failed on channels %s and %s\n", chan->name, peer->name);
04141          }
04142          goto before_you_go;
04143       }
04144       
04145       if (!f || (f->frametype == AST_FRAME_CONTROL &&
04146             (f->subclass.integer == AST_CONTROL_HANGUP || f->subclass.integer == AST_CONTROL_BUSY ||
04147                f->subclass.integer == AST_CONTROL_CONGESTION))) {
04148          /*
04149           * If the bridge was broken for a hangup that isn't real,
04150           * then don't run the h extension, because the channel isn't
04151           * really hung up. This should really only happen with AST_SOFTHANGUP_ASYNCGOTO,
04152           * but it doesn't hurt to check AST_SOFTHANGUP_UNBRIDGE either.
04153           */
04154          ast_channel_lock(chan);
04155          if (chan->_softhangup & (AST_SOFTHANGUP_ASYNCGOTO | AST_SOFTHANGUP_UNBRIDGE)) {
04156             ast_set_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT);
04157          }
04158          ast_channel_unlock(chan);
04159          res = -1;
04160          break;
04161       }
04162       /* many things should be sent to the 'other' channel */
04163       other = (who == chan) ? peer : chan;
04164       if (f->frametype == AST_FRAME_CONTROL) {
04165          switch (f->subclass.integer) {
04166          case AST_CONTROL_RINGING:
04167          case AST_CONTROL_FLASH:
04168          case -1:
04169             ast_indicate(other, f->subclass.integer);
04170             break;
04171          case AST_CONTROL_CONNECTED_LINE:
04172             if (!ast_channel_connected_line_macro(who, other, f, who != chan, 1)) {
04173                break;
04174             }
04175             ast_indicate_data(other, f->subclass.integer, f->data.ptr, f->datalen);
04176             break;
04177          case AST_CONTROL_REDIRECTING:
04178             if (!ast_channel_redirecting_macro(who, other, f, who != chan, 1)) {
04179                break;
04180             }
04181             ast_indicate_data(other, f->subclass.integer, f->data.ptr, f->datalen);
04182             break;
04183          case AST_CONTROL_AOC:
04184          case AST_CONTROL_HOLD:
04185          case AST_CONTROL_UNHOLD:
04186             ast_indicate_data(other, f->subclass.integer, f->data.ptr, f->datalen);
04187             break;
04188          case AST_CONTROL_OPTION:
04189             aoh = f->data.ptr;
04190             /* Forward option Requests, but only ones we know are safe
04191              * These are ONLY sent by chan_iax2 and I'm not convinced that
04192              * they are useful. I haven't deleted them entirely because I
04193              * just am not sure of the ramifications of removing them. */
04194             if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
04195                   switch (ntohs(aoh->option)) {
04196                case AST_OPTION_TONE_VERIFY:
04197                case AST_OPTION_TDD:
04198                case AST_OPTION_RELAXDTMF:
04199                case AST_OPTION_AUDIO_MODE:
04200                case AST_OPTION_DIGIT_DETECT:
04201                case AST_OPTION_FAX_DETECT:
04202                   ast_channel_setoption(other, ntohs(aoh->option), aoh->data, 
04203                      f->datalen - sizeof(struct ast_option_header), 0);
04204                }
04205             }
04206             break;
04207          }
04208       } else if (f->frametype == AST_FRAME_DTMF_BEGIN) {
04209          struct ast_flags *cfg;
04210          char dtmfcode[2] = { f->subclass.integer, };
04211          size_t featurelen;
04212 
04213          if (who == chan) {
04214             featurelen = strlen(chan_featurecode);
04215             cfg = &(config->features_caller);
04216          } else {
04217             featurelen = strlen(peer_featurecode);
04218             cfg = &(config->features_callee);
04219          }
04220          /* Take a peek if this (possibly) matches a feature. If not, just pass this
04221           * DTMF along untouched. If this is not the first digit of a multi-digit code
04222           * then we need to fall through and stream the characters if it matches */
04223          if (featurelen == 0
04224             && feature_check(chan, cfg, &dtmfcode[0]) == AST_FEATURE_RETURN_PASSDIGITS) {
04225             if (option_debug > 3) {
04226                ast_log(LOG_DEBUG, "Passing DTMF through, since it is not a feature code\n");
04227             }
04228             ast_write(other, f);
04229             sendingdtmfdigit = 1;
04230          } else {
04231             /* If ast_opt_transmit_silence is set, then we need to make sure we are
04232              * transmitting something while we hold on to the DTMF waiting for a
04233              * feature. */
04234             if (!silgen && ast_opt_transmit_silence) {
04235                silgen = ast_channel_start_silence_generator(other);
04236             }
04237             if (option_debug > 3) {
04238                ast_log(LOG_DEBUG, "Not passing DTMF through, since it may be a feature code\n");
04239             }
04240          }
04241       } else if (f->frametype == AST_FRAME_DTMF_END) {
04242          char *featurecode;
04243          int sense;
04244 
04245          hadfeatures = hasfeatures;
04246          /* This cannot overrun because the longest feature is one shorter than our buffer */
04247          if (who == chan) {
04248             sense = FEATURE_SENSE_CHAN;
04249             featurecode = chan_featurecode;
04250          } else  {
04251             sense = FEATURE_SENSE_PEER;
04252             featurecode = peer_featurecode;
04253          }
04254 
04255          if (sendingdtmfdigit == 1) {
04256             /* We let the BEGIN go through happily, so let's not bother with the END,
04257              * since we already know it's not something we bother with */
04258             ast_write(other, f);
04259             sendingdtmfdigit = 0;
04260          } else {
04261             /*! append the event to featurecode. we rely on the string being zero-filled, and
04262              * not overflowing it. 
04263              * \todo XXX how do we guarantee the latter ?
04264              */
04265             featurecode[strlen(featurecode)] = f->subclass.integer;
04266             /* Get rid of the frame before we start doing "stuff" with the channels */
04267             ast_frfree(f);
04268             f = NULL;
04269             if (silgen) {
04270                ast_channel_stop_silence_generator(other, silgen);
04271                silgen = NULL;
04272             }
04273             config->feature_timer = 0;
04274             res = feature_interpret(chan, peer, config, featurecode, sense);
04275             switch(res) {
04276             case AST_FEATURE_RETURN_PASSDIGITS:
04277                ast_dtmf_stream(other, who, featurecode, 0, 0);
04278                /* Fall through */
04279             case AST_FEATURE_RETURN_SUCCESS:
04280                memset(featurecode, 0, sizeof(chan_featurecode));
04281                break;
04282             }
04283             if (res >= AST_FEATURE_RETURN_PASSDIGITS) {
04284                res = 0;
04285             } else {
04286                break;
04287             }
04288             hasfeatures = !ast_strlen_zero(chan_featurecode) || !ast_strlen_zero(peer_featurecode);
04289             if (hadfeatures && !hasfeatures) {
04290                /* Feature completed or timed out */
04291                config->feature_timer = 0;
04292             } else if (hasfeatures) {
04293                if (config->timelimit) {
04294                   /* No warning next time - we are waiting for feature code */
04295                   ast_set_flag(config, AST_FEATURE_WARNING_ACTIVE);
04296                }
04297                config->feature_start_time = ast_tvnow();
04298                config->feature_timer = featuredigittimeout;
04299                ast_debug(1, "Set feature timer to %ld ms\n", config->feature_timer);
04300             }
04301          }
04302       }
04303       if (f)
04304          ast_frfree(f);
04305    }
04306    ast_cel_report_event(chan, AST_CEL_BRIDGE_END, NULL, NULL, peer);
04307 
04308 before_you_go:
04309    /* Just in case something weird happened and we didn't clean up the silence generator... */
04310    if (silgen) {
04311       ast_channel_stop_silence_generator(who == chan ? peer : chan, silgen);
04312       silgen = NULL;
04313    }
04314 
04315    if (ast_test_flag(chan,AST_FLAG_BRIDGE_HANGUP_DONT)) {
04316       ast_clear_flag(chan,AST_FLAG_BRIDGE_HANGUP_DONT); /* its job is done */
04317       if (bridge_cdr) {
04318          ast_cdr_discard(bridge_cdr);
04319          /* QUESTION: should we copy bridge_cdr fields to the peer before we throw it away? */
04320       }
04321       return res; /* if we shouldn't do the h-exten, we shouldn't do the bridge cdr, either! */
04322    }
04323 
04324    if (config->end_bridge_callback) {
04325       config->end_bridge_callback(config->end_bridge_callback_data);
04326    }
04327 
04328    /* run the hangup exten on the chan object IFF it was NOT involved in a parking situation 
04329     * if it were, then chan belongs to a different thread now, and might have been hung up long
04330      * ago.
04331     */
04332    if (ast_test_flag(&config->features_caller, AST_FEATURE_NO_H_EXTEN)) {
04333       h_context = NULL;
04334    } else if (ast_exists_extension(chan, chan->context, "h", 1,
04335       S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
04336       h_context = chan->context;
04337    } else if (!ast_strlen_zero(chan->macrocontext)
04338       && ast_exists_extension(chan, chan->macrocontext, "h", 1,
04339          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
04340       h_context = chan->macrocontext;
04341    } else {
04342       h_context = NULL;
04343    }
04344    if (h_context) {
04345       struct ast_cdr *swapper = NULL;
04346       char savelastapp[AST_MAX_EXTENSION];
04347       char savelastdata[AST_MAX_EXTENSION];
04348       char save_context[AST_MAX_CONTEXT];
04349       char save_exten[AST_MAX_EXTENSION];
04350       int  save_prio;
04351       int  found = 0;   /* set if we find at least one match */
04352       int  spawn_error = 0;
04353 
04354       /*
04355        * Make sure that the channel is marked as hungup since we are
04356        * going to run the "h" exten on it.
04357        */
04358       ast_softhangup(chan, AST_SOFTHANGUP_APPUNLOAD);
04359 
04360       autoloopflag = ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP);
04361       ast_set_flag(chan, AST_FLAG_IN_AUTOLOOP);
04362       if (bridge_cdr && ast_opt_end_cdr_before_h_exten) {
04363          ast_cdr_end(bridge_cdr);
04364       }
04365 
04366       /* swap the bridge cdr and the chan cdr for a moment, and let the endbridge
04367          dialplan code operate on it */
04368       ast_channel_lock(chan);
04369       if (bridge_cdr) {
04370          swapper = chan->cdr;
04371          ast_copy_string(savelastapp, bridge_cdr->lastapp, sizeof(bridge_cdr->lastapp));
04372          ast_copy_string(savelastdata, bridge_cdr->lastdata, sizeof(bridge_cdr->lastdata));
04373          chan->cdr = bridge_cdr;
04374       }
04375       ast_copy_string(save_context, chan->context, sizeof(save_context));
04376       ast_copy_string(save_exten, chan->exten, sizeof(save_exten));
04377       save_prio = chan->priority;
04378       if (h_context != chan->context) {
04379          ast_copy_string(chan->context, h_context, sizeof(chan->context));
04380       }
04381       ast_copy_string(chan->exten, "h", sizeof(chan->exten));
04382       chan->priority = 1;
04383       ast_channel_unlock(chan);
04384 
04385       while ((spawn_error = ast_spawn_extension(chan, chan->context, chan->exten,
04386          chan->priority,
04387          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL),
04388          &found, 1)) == 0) {
04389          chan->priority++;
04390       }
04391       if (found && spawn_error) {
04392          /* Something bad happened, or a hangup has been requested. */
04393          ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", chan->context, chan->exten, chan->priority, chan->name);
04394          ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", chan->context, chan->exten, chan->priority, chan->name);
04395       }
04396 
04397       /* swap it back */
04398       ast_channel_lock(chan);
04399       ast_copy_string(chan->context, save_context, sizeof(chan->context));
04400       ast_copy_string(chan->exten, save_exten, sizeof(chan->exten));
04401       chan->priority = save_prio;
04402       if (bridge_cdr) {
04403          if (chan->cdr == bridge_cdr) {
04404             chan->cdr = swapper;
04405          } else {
04406             bridge_cdr = NULL;
04407          }
04408       }
04409       /* An "h" exten has been run, so indicate that one has been run. */
04410       ast_set_flag(chan, AST_FLAG_BRIDGE_HANGUP_RUN);
04411       ast_channel_unlock(chan);
04412 
04413       /* protect the lastapp/lastdata against the effects of the hangup/dialplan code */
04414       if (bridge_cdr) {
04415          ast_copy_string(bridge_cdr->lastapp, savelastapp, sizeof(bridge_cdr->lastapp));
04416          ast_copy_string(bridge_cdr->lastdata, savelastdata, sizeof(bridge_cdr->lastdata));
04417       }
04418       ast_set2_flag(chan, autoloopflag, AST_FLAG_IN_AUTOLOOP);
04419    }
04420    
04421    /* obey the NoCDR() wishes. -- move the DISABLED flag to the bridge CDR if it was set on the channel during the bridge... */
04422    new_chan_cdr = pick_unlocked_cdr(chan->cdr); /* the proper chan cdr, if there are forked cdrs */
04423    /* If the channel CDR has been modified during the call, record the changes in the bridge cdr,
04424     * BUT, if we've gone through the h extension block above, the CDR got swapped so don't overwrite
04425     * what was done in the h extension. What a mess. This is why you never touch CDR code. */
04426    if (new_chan_cdr && bridge_cdr && !h_context) {
04427       ast_cdr_copy_vars(bridge_cdr, new_chan_cdr);
04428       ast_copy_string(bridge_cdr->userfield, new_chan_cdr->userfield, sizeof(bridge_cdr->userfield));
04429       bridge_cdr->amaflags = new_chan_cdr->amaflags;
04430       ast_copy_string(bridge_cdr->accountcode, new_chan_cdr->accountcode, sizeof(bridge_cdr->accountcode));
04431       if (ast_test_flag(new_chan_cdr, AST_CDR_FLAG_POST_DISABLED)) {
04432          ast_set_flag(bridge_cdr, AST_CDR_FLAG_POST_DISABLED);
04433       }
04434    }
04435 
04436    /* we can post the bridge CDR at this point */
04437    if (bridge_cdr) {
04438       ast_cdr_end(bridge_cdr);
04439       ast_cdr_detach(bridge_cdr);
04440    }
04441    
04442    /* do a specialized reset on the beginning channel
04443       CDR's, if they still exist, so as not to mess up
04444       issues in future bridges;
04445       
04446       Here are the rules of the game:
04447       1. The chan and peer channel pointers will not change
04448          during the life of the bridge.
04449       2. But, in transfers, the channel names will change.
04450          between the time the bridge is started, and the
04451          time the channel ends. 
04452          Usually, when a channel changes names, it will
04453          also change CDR pointers.
04454       3. Usually, only one of the two channels (chan or peer)
04455          will change names.
04456       4. Usually, if a channel changes names during a bridge,
04457          it is because of a transfer. Usually, in these situations,
04458          it is normal to see 2 bridges running simultaneously, and
04459          it is not unusual to see the two channels that change
04460          swapped between bridges.
04461       5. After a bridge occurs, we have 2 or 3 channels' CDRs
04462          to attend to; if the chan or peer changed names,
04463          we have the before and after attached CDR's.
04464    */
04465 
04466    if (new_chan_cdr) {
04467       struct ast_channel *chan_ptr = NULL;
04468 
04469       if (strcasecmp(orig_channame, chan->name) != 0) { 
04470          /* old channel */
04471          if ((chan_ptr = ast_channel_get_by_name(orig_channame))) {
04472             ast_channel_lock(chan_ptr);
04473             if (!ast_bridged_channel(chan_ptr)) {
04474                struct ast_cdr *cur;
04475                for (cur = chan_ptr->cdr; cur; cur = cur->next) {
04476                   if (cur == chan_cdr) {
04477                      break;
04478                   }
04479                }
04480                if (cur) {
04481                   ast_cdr_specialized_reset(chan_cdr, 0);
04482                }
04483             }
04484             ast_channel_unlock(chan_ptr);
04485             chan_ptr = ast_channel_unref(chan_ptr);
04486          }
04487          /* new channel */
04488          ast_cdr_specialized_reset(new_chan_cdr, 0);
04489       } else {
04490          ast_cdr_specialized_reset(chan->cdr, 0); /* nothing changed, reset the chan cdr  */
04491       }
04492    }
04493 
04494    {
04495       struct ast_channel *chan_ptr = NULL;
04496       new_peer_cdr = pick_unlocked_cdr(peer->cdr); /* the proper chan cdr, if there are forked cdrs */
04497       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))
04498          ast_set_flag(new_peer_cdr, AST_CDR_FLAG_POST_DISABLED); /* DISABLED is viral-- it will propagate across a bridge */
04499       if (strcasecmp(orig_peername, peer->name) != 0) { 
04500          /* old channel */
04501          if ((chan_ptr = ast_channel_get_by_name(orig_peername))) {
04502             ast_channel_lock(chan_ptr);
04503             if (!ast_bridged_channel(chan_ptr)) {
04504                struct ast_cdr *cur;
04505                for (cur = chan_ptr->cdr; cur; cur = cur->next) {
04506                   if (cur == peer_cdr) {
04507                      break;
04508                   }
04509                }
04510                if (cur) {
04511                   ast_cdr_specialized_reset(peer_cdr, 0);
04512                }
04513             }
04514             ast_channel_unlock(chan_ptr);
04515             chan_ptr = ast_channel_unref(chan_ptr);
04516          }
04517          /* new channel */
04518          if (new_peer_cdr) {
04519             ast_cdr_specialized_reset(new_peer_cdr, 0);
04520          }
04521       } else {
04522          if (we_disabled_peer_cdr) {
04523             ast_clear_flag(peer->cdr, AST_CDR_FLAG_POST_DISABLED);
04524          }
04525          ast_cdr_specialized_reset(peer->cdr, 0); /* nothing changed, reset the peer cdr  */
04526       }
04527    }
04528    
04529    return res;
04530 }
04531 
04532 /*! \brief Output parking event to manager */
04533 static void post_manager_event(const char *s, struct parkeduser *pu)
04534 {
04535    manager_event(EVENT_FLAG_CALL, s,
04536       "Exten: %s\r\n"
04537       "Channel: %s\r\n"
04538       "Parkinglot: %s\r\n"
04539       "CallerIDNum: %s\r\n"
04540       "CallerIDName: %s\r\n"
04541       "ConnectedLineNum: %s\r\n"
04542       "ConnectedLineName: %s\r\n"
04543       "UniqueID: %s\r\n",
04544       pu->parkingexten, 
04545       pu->chan->name,
04546       pu->parkinglot->name,
04547       S_COR(pu->chan->caller.id.number.valid, pu->chan->caller.id.number.str, "<unknown>"),
04548       S_COR(pu->chan->caller.id.name.valid, pu->chan->caller.id.name.str, "<unknown>"),
04549       S_COR(pu->chan->connected.id.number.valid, pu->chan->connected.id.number.str, "<unknown>"),
04550       S_COR(pu->chan->connected.id.name.valid, pu->chan->connected.id.name.str, "<unknown>"),
04551       pu->chan->uniqueid
04552       );
04553 }
04554 
04555 static char *callback_dialoptions(struct ast_flags *features_callee, struct ast_flags *features_caller, char *options, size_t len)
04556 {
04557    int i = 0;
04558    enum {
04559       OPT_CALLEE_REDIRECT   = 't',
04560       OPT_CALLER_REDIRECT   = 'T',
04561       OPT_CALLEE_AUTOMON    = 'w',
04562       OPT_CALLER_AUTOMON    = 'W',
04563       OPT_CALLEE_DISCONNECT = 'h',
04564       OPT_CALLER_DISCONNECT = 'H',
04565       OPT_CALLEE_PARKCALL   = 'k',
04566       OPT_CALLER_PARKCALL   = 'K',
04567    };
04568 
04569    memset(options, 0, len);
04570    if (ast_test_flag(features_caller, AST_FEATURE_REDIRECT) && i < len) {
04571       options[i++] = OPT_CALLER_REDIRECT;
04572    }
04573    if (ast_test_flag(features_caller, AST_FEATURE_AUTOMON) && i < len) {
04574       options[i++] = OPT_CALLER_AUTOMON;
04575    }
04576    if (ast_test_flag(features_caller, AST_FEATURE_DISCONNECT) && i < len) {
04577       options[i++] = OPT_CALLER_DISCONNECT;
04578    }
04579    if (ast_test_flag(features_caller, AST_FEATURE_PARKCALL) && i < len) {
04580       options[i++] = OPT_CALLER_PARKCALL;
04581    }
04582 
04583    if (ast_test_flag(features_callee, AST_FEATURE_REDIRECT) && i < len) {
04584       options[i++] = OPT_CALLEE_REDIRECT;
04585    }
04586    if (ast_test_flag(features_callee, AST_FEATURE_AUTOMON) && i < len) {
04587       options[i++] = OPT_CALLEE_AUTOMON;
04588    }
04589    if (ast_test_flag(features_callee, AST_FEATURE_DISCONNECT) && i < len) {
04590       options[i++] = OPT_CALLEE_DISCONNECT;
04591    }
04592    if (ast_test_flag(features_callee, AST_FEATURE_PARKCALL) && i < len) {
04593       options[i++] = OPT_CALLEE_PARKCALL;
04594    }
04595 
04596    return options;
04597 }
04598 
04599 /*!
04600  * \internal
04601  * \brief Run management on a parked call.
04602  *
04603  * \note The parkinglot parkings list is locked on entry.
04604  *
04605  * \retval TRUE if the parking completed.
04606  */
04607 static int manage_parked_call(struct parkeduser *pu, const struct pollfd *pfds, int nfds, struct pollfd **new_pfds, int *new_nfds, int *ms)
04608 {
04609    struct ast_channel *chan = pu->chan;   /* shorthand */
04610    int tms;        /* timeout for this item */
04611    int x;          /* fd index in channel */
04612 
04613    tms = ast_tvdiff_ms(ast_tvnow(), pu->start);
04614    if (tms > pu->parkingtime) {
04615       /*
04616        * Call has been parked too long.
04617        * Stop entertaining the caller.
04618        */
04619       switch (pu->hold_method) {
04620       case AST_CONTROL_HOLD:
04621          ast_indicate(pu->chan, AST_CONTROL_UNHOLD);
04622          break;
04623       case AST_CONTROL_RINGING:
04624          ast_indicate(pu->chan, -1);
04625          break;
04626       default:
04627          break;
04628       }
04629       pu->hold_method = 0;
04630 
04631       /* Get chan, exten from derived kludge */
04632       if (pu->peername[0]) {
04633          char *peername;
04634          char *dash;
04635          char *peername_flat; /* using something like DAHDI/52 for an extension name is NOT a good idea */
04636          int i;
04637 
04638          peername = ast_strdupa(pu->peername);
04639          dash = strrchr(peername, '-');
04640          if (dash) {
04641             *dash = '\0';
04642          }
04643 
04644          peername_flat = ast_strdupa(peername);
04645          for (i = 0; peername_flat[i]; i++) {
04646             if (peername_flat[i] == '/') {
04647                peername_flat[i] = '_';
04648             }
04649          }
04650 
04651          if (!ast_context_find_or_create(NULL, NULL, parking_con_dial, registrar)) {
04652             ast_log(LOG_ERROR,
04653                "Parking dial context '%s' does not exist and unable to create\n",
04654                parking_con_dial);
04655          } else {
04656             char returnexten[AST_MAX_EXTENSION];
04657             struct ast_datastore *features_datastore;
04658             struct ast_dial_features *dialfeatures;
04659 
04660             if (!strncmp(peername, "Parked/", 7)) {
04661                peername += 7;
04662             }
04663 
04664             ast_channel_lock(chan);
04665             features_datastore = ast_channel_datastore_find(chan, &dial_features_info,
04666                NULL);
04667             if (features_datastore && (dialfeatures = features_datastore->data)) {
04668                char buf[MAX_DIAL_FEATURE_OPTIONS] = {0,};
04669 
04670                snprintf(returnexten, sizeof(returnexten), "%s,30,%s", peername,
04671                   callback_dialoptions(&dialfeatures->peer_features,
04672                      &dialfeatures->my_features, buf, sizeof(buf)));
04673             } else { /* Existing default */
04674                ast_log(LOG_NOTICE, "Dial features not found on %s, using default!\n",
04675                   chan->name);
04676                snprintf(returnexten, sizeof(returnexten), "%s,30,t", peername);
04677             }
04678             ast_channel_unlock(chan);
04679 
04680             if (ast_add_extension(parking_con_dial, 1, peername_flat, 1, NULL, NULL,
04681                "Dial", ast_strdup(returnexten), ast_free_ptr, registrar)) {
04682                ast_log(LOG_ERROR,
04683                   "Could not create parking return dial exten: %s@%s\n",
04684                   peername_flat, parking_con_dial);
04685             }
04686          }
04687          if (pu->options_specified) {
04688             /*
04689              * Park() was called with overriding return arguments, respect
04690              * those arguments.
04691              */
04692             set_c_e_p(chan, pu->context, pu->exten, pu->priority);
04693          } else if (comebacktoorigin) {
04694             set_c_e_p(chan, parking_con_dial, peername_flat, 1);
04695          } else {
04696             char parkingslot[AST_MAX_EXTENSION];
04697 
04698             snprintf(parkingslot, sizeof(parkingslot), "%d", pu->parkingnum);
04699             pbx_builtin_setvar_helper(chan, "PARKINGSLOT", parkingslot);
04700             set_c_e_p(chan, "parkedcallstimeout", peername_flat, 1);
04701          }
04702       } else {
04703          /*
04704           * They've been waiting too long, send them back to where they
04705           * came.  Theoretically they should have their original
04706           * extensions and such, but we copy to be on the safe side.
04707           */
04708          set_c_e_p(chan, pu->context, pu->exten, pu->priority);
04709       }
04710       post_manager_event("ParkedCallTimeOut", pu);
04711       ast_cel_report_event(pu->chan, AST_CEL_PARK_END, NULL, "ParkedCallTimeOut", NULL);
04712 
04713       ast_verb(2, "Timeout for %s parked on %d (%s). Returning to %s,%s,%d\n",
04714          pu->chan->name, pu->parkingnum, pu->parkinglot->name, pu->chan->context,
04715          pu->chan->exten, pu->chan->priority);
04716 
04717       /* Start up the PBX, or hang them up */
04718       if (ast_pbx_start(chan))  {
04719          ast_log(LOG_WARNING,
04720             "Unable to restart the PBX for user on '%s', hanging them up...\n",
04721             pu->chan->name);
04722          ast_hangup(chan);
04723       }
04724 
04725       /* And take them out of the parking lot */
04726       return 1;
04727    }
04728 
04729    /* still within parking time, process descriptors */
04730    if (pfds) {
04731       for (x = 0; x < AST_MAX_FDS; x++) {
04732          struct ast_frame *f;
04733          int y;
04734 
04735          if (chan->fds[x] == -1) {
04736             continue;   /* nothing on this descriptor */
04737          }
04738 
04739          for (y = 0; y < nfds; y++) {
04740             if (pfds[y].fd == chan->fds[x]) {
04741                /* Found poll record! */
04742                break;
04743             }
04744          }
04745          if (y == nfds) {
04746             /* Not found */
04747             continue;
04748          }
04749 
04750          if (!(pfds[y].revents & (POLLIN | POLLERR | POLLPRI))) {
04751             /* Next x */
04752             continue;
04753          }
04754 
04755          if (pfds[y].revents & POLLPRI) {
04756             ast_set_flag(chan, AST_FLAG_EXCEPTION);
04757          } else {
04758             ast_clear_flag(chan, AST_FLAG_EXCEPTION);
04759          }
04760          chan->fdno = x;
04761 
04762          /* See if they need servicing */
04763          f = ast_read(pu->chan);
04764          /* Hangup? */
04765          if (!f || (f->frametype == AST_FRAME_CONTROL
04766             && f->subclass.integer == AST_CONTROL_HANGUP)) {
04767             if (f) {
04768                ast_frfree(f);
04769             }
04770             post_manager_event("ParkedCallGiveUp", pu);
04771             ast_cel_report_event(pu->chan, AST_CEL_PARK_END, NULL, "ParkedCallGiveUp",
04772                NULL);
04773 
04774             /* There's a problem, hang them up */
04775             ast_verb(2, "%s got tired of being parked\n", chan->name);
04776             ast_hangup(chan);
04777 
04778             /* And take them out of the parking lot */
04779             return 1;
04780          } else {
04781             /* XXX Maybe we could do something with packets, like dial "0" for operator or something XXX */
04782             ast_frfree(f);
04783             if (pu->hold_method == AST_CONTROL_HOLD
04784                && pu->moh_trys < 3
04785                && !chan->generatordata) {
04786                ast_debug(1,
04787                   "MOH on parked call stopped by outside source.  Restarting on channel %s.\n",
04788                   chan->name);
04789                ast_indicate_data(chan, AST_CONTROL_HOLD,
04790                   S_OR(pu->parkinglot->cfg.mohclass, NULL),
04791                   (!ast_strlen_zero(pu->parkinglot->cfg.mohclass)
04792                      ? strlen(pu->parkinglot->cfg.mohclass) + 1 : 0));
04793                pu->moh_trys++;
04794             }
04795             break;
04796          }
04797       } /* End for */
04798    }
04799 
04800    /* mark fds for next round */
04801    for (x = 0; x < AST_MAX_FDS; x++) {
04802       if (chan->fds[x] > -1) {
04803          void *tmp = ast_realloc(*new_pfds,
04804             (*new_nfds + 1) * sizeof(struct pollfd));
04805 
04806          if (!tmp) {
04807             continue;
04808          }
04809          *new_pfds = tmp;
04810          (*new_pfds)[*new_nfds].fd = chan->fds[x];
04811          (*new_pfds)[*new_nfds].events = POLLIN | POLLERR | POLLPRI;
04812          (*new_pfds)[*new_nfds].revents = 0;
04813          (*new_nfds)++;
04814       }
04815    }
04816    /* Keep track of our shortest wait */
04817    if (tms < *ms || *ms < 0) {
04818       *ms = tms;
04819    }
04820 
04821    /* Stay in the parking lot. */
04822    return 0;
04823 }
04824 
04825 /*! \brief Run management on parkinglots, called once per parkinglot */
04826 static void manage_parkinglot(struct ast_parkinglot *curlot, const struct pollfd *pfds, int nfds, struct pollfd **new_pfds, int *new_nfds, int *ms)
04827 {
04828    struct parkeduser *pu;
04829    struct ast_context *con;
04830 
04831    /* Lock parkings list */
04832    AST_LIST_LOCK(&curlot->parkings);
04833    AST_LIST_TRAVERSE_SAFE_BEGIN(&curlot->parkings, pu, list) {
04834       if (pu->notquiteyet) { /* Pretend this one isn't here yet */
04835          continue;
04836       }
04837       if (manage_parked_call(pu, pfds, nfds, new_pfds, new_nfds, ms)) {
04838          /* Parking is complete for this call so remove it from the parking lot. */
04839          con = ast_context_find(pu->parkinglot->cfg.parking_con);
04840          if (con) {
04841             if (ast_context_remove_extension2(con, pu->parkingexten, 1, NULL, 0)) {
04842                ast_log(LOG_WARNING,
04843                   "Whoa, failed to remove the parking extension %s@%s!\n",
04844                   pu->parkingexten, pu->parkinglot->cfg.parking_con);
04845             }
04846             notify_metermaids(pu->parkingexten, pu->parkinglot->cfg.parking_con,
04847                AST_DEVICE_NOT_INUSE);
04848          } else {
04849             ast_log(LOG_WARNING,
04850                "Whoa, parking lot '%s' context '%s' does not exist.\n",
04851                pu->parkinglot->name, pu->parkinglot->cfg.parking_con);
04852          }
04853          AST_LIST_REMOVE_CURRENT(list);
04854          parkinglot_unref(pu->parkinglot);
04855          ast_free(pu);
04856       }
04857    }
04858    AST_LIST_TRAVERSE_SAFE_END;
04859    AST_LIST_UNLOCK(&curlot->parkings);
04860 }
04861 
04862 /*! 
04863  * \brief Take care of parked calls and unpark them if needed 
04864  * \param ignore unused var.
04865  * 
04866  * Start inf loop, lock parking lot, check if any parked channels have gone above timeout
04867  * if so, remove channel from parking lot and return it to the extension that parked it.
04868  * Check if parked channel decided to hangup, wait until next FD via select().
04869  */
04870 static void *do_parking_thread(void *ignore)
04871 {
04872    struct pollfd *pfds = NULL, *new_pfds = NULL;
04873    int nfds = 0, new_nfds = 0;
04874 
04875    for (;;) {
04876       struct ao2_iterator iter;
04877       struct ast_parkinglot *curlot;
04878       int ms = -1;   /* poll2 timeout, uninitialized */
04879 
04880       iter = ao2_iterator_init(parkinglots, 0);
04881       while ((curlot = ao2_iterator_next(&iter))) {
04882          manage_parkinglot(curlot, pfds, nfds, &new_pfds, &new_nfds, &ms);
04883          ao2_ref(curlot, -1);
04884       }
04885       ao2_iterator_destroy(&iter);
04886 
04887       /* Recycle */
04888       ast_free(pfds);
04889       pfds = new_pfds;
04890       nfds = new_nfds;
04891       new_pfds = NULL;
04892       new_nfds = 0;
04893 
04894       /* Wait for something to happen */
04895       ast_poll(pfds, nfds, ms);
04896       pthread_testcancel();
04897    }
04898    /* If this WERE reached, we'd need to free(pfds) */
04899    return NULL;   /* Never reached */
04900 }
04901 
04902 /*! \brief Find parkinglot by name */
04903 static struct ast_parkinglot *find_parkinglot(const char *name)
04904 {
04905    struct ast_parkinglot *parkinglot;
04906 
04907    if (ast_strlen_zero(name)) {
04908       return NULL;
04909    }
04910 
04911    parkinglot = ao2_find(parkinglots, (void *) name, 0);
04912    if (parkinglot) {
04913       ast_debug(1, "Found Parking lot: %s\n", parkinglot->name);
04914    }
04915 
04916    return parkinglot;
04917 }
04918 
04919 /*! \brief Copy parkinglot and store it with new name */
04920 static struct ast_parkinglot *copy_parkinglot(const char *name, const struct ast_parkinglot *parkinglot)
04921 {
04922    struct ast_parkinglot *copylot;
04923 
04924    if ((copylot = find_parkinglot(name))) { /* Parkinglot with that name already exists */
04925       ao2_ref(copylot, -1);
04926       return NULL;
04927    }
04928 
04929    copylot = create_parkinglot(name);
04930    if (!copylot) {
04931       return NULL;
04932    }
04933 
04934    ast_debug(1, "Building parking lot %s\n", name);
04935 
04936    /* Copy the source parking lot configuration. */
04937    copylot->cfg = parkinglot->cfg;
04938 
04939    return copylot;
04940 }
04941 
04942 AST_APP_OPTIONS(park_call_options, BEGIN_OPTIONS
04943    AST_APP_OPTION('r', AST_PARK_OPT_RINGING),
04944    AST_APP_OPTION('R', AST_PARK_OPT_RANDOMIZE),
04945    AST_APP_OPTION('s', AST_PARK_OPT_SILENCE),
04946 END_OPTIONS );
04947 
04948 /*! \brief Park a call */
04949 static int park_call_exec(struct ast_channel *chan, const char *data)
04950 {
04951    struct ast_park_call_args args = { 0, };
04952    struct ast_flags flags = { 0 };
04953    char orig_exten[AST_MAX_EXTENSION];
04954    int orig_priority;
04955    int res;
04956    const char *pl_name;
04957    char *parse;
04958    struct park_app_args app_args;
04959 
04960    /*
04961     * Cache the original channel name because we are going to
04962     * masquerade the channel.  Prefer the BLINDTRANSFER channel
04963     * name over this channel name.  BLINDTRANSFER could be set if
04964     * the parking access extension did not get detected and we are
04965     * executing the Park application from the dialplan.
04966     *
04967     * The orig_chan_name is used to return the call to the
04968     * originator on parking timeout.
04969     */
04970    args.orig_chan_name = ast_strdupa(S_OR(
04971       pbx_builtin_getvar_helper(chan, "BLINDTRANSFER"), chan->name));
04972 
04973    /* Answer if call is not up */
04974    if (chan->_state != AST_STATE_UP) {
04975       if (ast_answer(chan)) {
04976          return -1;
04977       }
04978 
04979       /* Sleep to allow VoIP streams to settle down */
04980       if (ast_safe_sleep(chan, 1000)) {
04981          return -1;
04982       }
04983    }
04984 
04985    /* Process the dialplan application options. */
04986    parse = ast_strdupa(data);
04987    AST_STANDARD_APP_ARGS(app_args, parse);
04988 
04989    if (!ast_strlen_zero(app_args.timeout)) {
04990       if (sscanf(app_args.timeout, "%30d", &args.timeout) != 1) {
04991          ast_log(LOG_WARNING, "Invalid timeout '%s' provided\n", app_args.timeout);
04992          args.timeout = 0;
04993       }
04994    }
04995    if (!ast_strlen_zero(app_args.return_con)) {
04996       args.return_con = app_args.return_con;
04997    }
04998    if (!ast_strlen_zero(app_args.return_ext)) {
04999       args.return_ext = app_args.return_ext;
05000    }
05001    if (!ast_strlen_zero(app_args.return_pri)) {
05002       if (sscanf(app_args.return_pri, "%30d", &args.return_pri) != 1) {
05003          ast_log(LOG_WARNING, "Invalid priority '%s' specified\n", app_args.return_pri);
05004          args.return_pri = 0;
05005       }
05006    }
05007 
05008    ast_app_parse_options(park_call_options, &flags, NULL, app_args.options);
05009    args.flags = flags.flags;
05010 
05011    /*
05012     * Setup the exten/priority to be s/1 since we don't know where
05013     * this call should return.
05014     */
05015    ast_copy_string(orig_exten, chan->exten, sizeof(orig_exten));
05016    orig_priority = chan->priority;
05017    strcpy(chan->exten, "s");
05018    chan->priority = 1;
05019 
05020    /* Park the call */
05021    if (!ast_strlen_zero(app_args.pl_name)) {
05022       pl_name = app_args.pl_name;
05023    } else {
05024       pl_name = findparkinglotname(chan);
05025    }
05026    if (ast_strlen_zero(pl_name)) {
05027       /* Parking lot is not specified, so use the default parking lot. */
05028       args.parkinglot = parkinglot_addref(default_parkinglot);
05029    } else {
05030       args.parkinglot = find_parkinglot(pl_name);
05031       if (!args.parkinglot && parkeddynamic) {
05032          args.parkinglot = create_dynamic_parkinglot(pl_name, chan);
05033       }
05034    }
05035    if (args.parkinglot) {
05036       res = masq_park_call(chan, chan, &args);
05037       parkinglot_unref(args.parkinglot);
05038    } else {
05039       /* Parking failed because the parking lot does not exist. */
05040       if (!ast_test_flag(&args, AST_PARK_OPT_SILENCE)) {
05041          ast_stream_and_wait(chan, "pbx-parkingfailed", "");
05042       }
05043       res = -1;
05044    }
05045    if (res) {
05046       /* Park failed, try to continue in the dialplan. */
05047       ast_copy_string(chan->exten, orig_exten, sizeof(chan->exten));
05048       chan->priority = orig_priority;
05049       res = 0;
05050    } else {
05051       /* Park succeeded. */
05052       res = -1;
05053    }
05054 
05055    return res;
05056 }
05057 
05058 /*! \brief Pickup parked call */
05059 static int parked_call_exec(struct ast_channel *chan, const char *data)
05060 {
05061    int res;
05062    struct ast_channel *peer = NULL;
05063    struct parkeduser *pu;
05064    struct ast_context *con;
05065    char *parse;
05066    const char *pl_name;
05067    int park = 0;
05068    struct ast_bridge_config config;
05069    struct ast_parkinglot *parkinglot;
05070    AST_DECLARE_APP_ARGS(app_args,
05071       AST_APP_ARG(pl_space);  /*!< Parking lot space to retrieve if present. */
05072       AST_APP_ARG(pl_name);   /*!< Parking lot name to use if present. */
05073       AST_APP_ARG(dummy);     /*!< Place to put any remaining args string. */
05074    );
05075 
05076    parse = ast_strdupa(data);
05077    AST_STANDARD_APP_ARGS(app_args, parse);
05078 
05079    if (!ast_strlen_zero(app_args.pl_space)) {
05080       if (sscanf(app_args.pl_space, "%30u", &park) != 1) {
05081          ast_log(LOG_WARNING, "Specified parking extension not a number: %s\n",
05082             app_args.pl_space);
05083          park = -1;
05084       }
05085    }
05086 
05087    if (!ast_strlen_zero(app_args.pl_name)) {
05088       pl_name = app_args.pl_name;
05089    } else {
05090       pl_name = findparkinglotname(chan);
05091    }
05092    if (ast_strlen_zero(pl_name)) {
05093       /* Parking lot is not specified, so use the default parking lot. */
05094       parkinglot = parkinglot_addref(default_parkinglot);
05095    } else {
05096       parkinglot = find_parkinglot(pl_name);
05097       if (!parkinglot) {
05098          /* It helps to answer the channel if not already up. :) */
05099          if (chan->_state != AST_STATE_UP) {
05100             ast_answer(chan);
05101          }
05102          if (ast_stream_and_wait(chan, "pbx-invalidpark", "")) {
05103             ast_log(LOG_WARNING, "ast_streamfile of %s failed on %s\n",
05104                "pbx-invalidpark", chan->name);
05105          }
05106          ast_log(LOG_WARNING,
05107             "Channel %s tried to retrieve parked call from unknown parking lot '%s'\n",
05108             chan->name, pl_name);
05109          return -1;
05110       }
05111    }
05112 
05113    AST_LIST_LOCK(&parkinglot->parkings);
05114    AST_LIST_TRAVERSE_SAFE_BEGIN(&parkinglot->parkings, pu, list) {
05115       if ((ast_strlen_zero(app_args.pl_space) || pu->parkingnum == park)
05116          && !pu->notquiteyet && !pu->chan->pbx) {
05117          /* The parking space has a call and can be picked up now. */
05118          AST_LIST_REMOVE_CURRENT(list);
05119          break;
05120       }
05121    }
05122    AST_LIST_TRAVERSE_SAFE_END;
05123    if (pu) {
05124       /* Found a parked call to pickup. */
05125       peer = pu->chan;
05126       con = ast_context_find(parkinglot->cfg.parking_con);
05127       if (con) {
05128          if (ast_context_remove_extension2(con, pu->parkingexten, 1, NULL, 0)) {
05129             ast_log(LOG_WARNING, "Whoa, failed to remove the extension!\n");
05130          } else {
05131             notify_metermaids(pu->parkingexten, parkinglot->cfg.parking_con, AST_DEVICE_NOT_INUSE);
05132          }
05133       } else {
05134          ast_log(LOG_WARNING, "Whoa, no parking context?\n");
05135       }
05136 
05137       ast_cel_report_event(pu->chan, AST_CEL_PARK_END, NULL, "UnParkedCall", chan);
05138       ast_manager_event(pu->chan, EVENT_FLAG_CALL, "UnParkedCall",
05139          "Exten: %s\r\n"
05140          "Channel: %s\r\n"
05141          "Parkinglot: %s\r\n"
05142          "From: %s\r\n"
05143          "CallerIDNum: %s\r\n"
05144          "CallerIDName: %s\r\n"
05145          "ConnectedLineNum: %s\r\n"
05146          "ConnectedLineName: %s\r\n"
05147          "Uniqueid: %s\r\n",
05148          pu->parkingexten, pu->chan->name, pu->parkinglot->name, chan->name,
05149          S_COR(pu->chan->caller.id.number.valid, pu->chan->caller.id.number.str, "<unknown>"),
05150          S_COR(pu->chan->caller.id.name.valid, pu->chan->caller.id.name.str, "<unknown>"),
05151          S_COR(pu->chan->connected.id.number.valid, pu->chan->connected.id.number.str, "<unknown>"),
05152          S_COR(pu->chan->connected.id.name.valid, pu->chan->connected.id.name.str, "<unknown>"),
05153          pu->chan->uniqueid
05154          );
05155 
05156       /* Stop entertaining the caller. */
05157       switch (pu->hold_method) {
05158       case AST_CONTROL_HOLD:
05159          ast_indicate(pu->chan, AST_CONTROL_UNHOLD);
05160          break;
05161       case AST_CONTROL_RINGING:
05162          ast_indicate(pu->chan, -1);
05163          break;
05164       default:
05165          break;
05166       }
05167       pu->hold_method = 0;
05168 
05169       parkinglot_unref(pu->parkinglot);
05170       ast_free(pu);
05171    }
05172    AST_LIST_UNLOCK(&parkinglot->parkings);
05173 
05174    if (peer) {
05175       /* Update connected line between retrieving call and parked call. */
05176       struct ast_party_connected_line connected;
05177 
05178       ast_party_connected_line_init(&connected);
05179 
05180       /* Send our caller-id to peer. */
05181       ast_channel_lock(chan);
05182       ast_connected_line_copy_from_caller(&connected, &chan->caller);
05183       ast_channel_unlock(chan);
05184       connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
05185       if (ast_channel_connected_line_macro(chan, peer, &connected, 0, 0)) {
05186          ast_channel_update_connected_line(peer, &connected, NULL);
05187       }
05188 
05189       /*
05190        * Get caller-id from peer.
05191        *
05192        * Update the retrieving call before it is answered if possible
05193        * for best results.  Some phones do not support updating the
05194        * connected line information after connection.
05195        */
05196       ast_channel_lock(peer);
05197       ast_connected_line_copy_from_caller(&connected, &peer->caller);
05198       ast_channel_unlock(peer);
05199       connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
05200       if (ast_channel_connected_line_macro(peer, chan, &connected, 1, 0)) {
05201          ast_channel_update_connected_line(chan, &connected, NULL);
05202       }
05203 
05204       ast_party_connected_line_free(&connected);
05205    }
05206 
05207    /* JK02: it helps to answer the channel if not already up */
05208    if (chan->_state != AST_STATE_UP) {
05209       ast_answer(chan);
05210    }
05211 
05212    if (peer) {
05213       struct ast_datastore *features_datastore;
05214       struct ast_dial_features *dialfeatures;
05215 
05216       /* Play a courtesy to the source(s) configured to prefix the bridge connecting */
05217       if (!ast_strlen_zero(courtesytone)) {
05218          static const char msg[] = "courtesy tone";
05219 
05220          switch (parkedplay) {
05221          case 0:/* Courtesy tone to pickup chan */
05222             res = play_message_to_chans(chan, peer, -1, msg, courtesytone);
05223             break;
05224          case 1:/* Courtesy tone to parked chan */
05225             res = play_message_to_chans(chan, peer, 1, msg, courtesytone);
05226             break;
05227          case 2:/* Courtesy tone to both chans */
05228             res = play_message_to_chans(chan, peer, 0, msg, courtesytone);
05229             break;
05230          default:
05231             res = 0;
05232             break;
05233          }
05234          if (res) {
05235             ast_hangup(peer);
05236             parkinglot_unref(parkinglot);
05237             return -1;
05238          }
05239       }
05240 
05241       res = ast_channel_make_compatible(chan, peer);
05242       if (res < 0) {
05243          ast_log(LOG_WARNING, "Could not make channels %s and %s compatible for bridge\n", chan->name, peer->name);
05244          ast_hangup(peer);
05245          parkinglot_unref(parkinglot);
05246          return -1;
05247       }
05248       /* This runs sorta backwards, since we give the incoming channel control, as if it
05249          were the person called. */
05250       ast_verb(3, "Channel %s connected to parked call %d\n", chan->name, park);
05251 
05252       pbx_builtin_setvar_helper(chan, "PARKEDCHANNEL", peer->name);
05253       ast_cdr_setdestchan(chan->cdr, peer->name);
05254       memset(&config, 0, sizeof(struct ast_bridge_config));
05255 
05256       /* Get datastore for peer and apply it's features to the callee side of the bridge config */
05257       ast_channel_lock(peer);
05258       features_datastore = ast_channel_datastore_find(peer, &dial_features_info, NULL);
05259       if (features_datastore && (dialfeatures = features_datastore->data)) {
05260          ast_copy_flags(&config.features_callee, &dialfeatures->my_features,
05261             AST_FLAGS_ALL);
05262       }
05263       ast_channel_unlock(peer);
05264 
05265       if ((parkinglot->cfg.parkedcalltransfers == AST_FEATURE_FLAG_BYCALLEE) || (parkinglot->cfg.parkedcalltransfers == AST_FEATURE_FLAG_BYBOTH)) {
05266          ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
05267       }
05268       if ((parkinglot->cfg.parkedcalltransfers == AST_FEATURE_FLAG_BYCALLER) || (parkinglot->cfg.parkedcalltransfers == AST_FEATURE_FLAG_BYBOTH)) {
05269          ast_set_flag(&(config.features_caller), AST_FEATURE_REDIRECT);
05270       }
05271       if ((parkinglot->cfg.parkedcallreparking == AST_FEATURE_FLAG_BYCALLEE) || (parkinglot->cfg.parkedcallreparking == AST_FEATURE_FLAG_BYBOTH)) {
05272          ast_set_flag(&(config.features_callee), AST_FEATURE_PARKCALL);
05273       }
05274       if ((parkinglot->cfg.parkedcallreparking == AST_FEATURE_FLAG_BYCALLER) || (parkinglot->cfg.parkedcallreparking == AST_FEATURE_FLAG_BYBOTH)) {
05275          ast_set_flag(&(config.features_caller), AST_FEATURE_PARKCALL);
05276       }
05277       if ((parkinglot->cfg.parkedcallhangup == AST_FEATURE_FLAG_BYCALLEE) || (parkinglot->cfg.parkedcallhangup == AST_FEATURE_FLAG_BYBOTH)) {
05278          ast_set_flag(&(config.features_callee), AST_FEATURE_DISCONNECT);
05279       }
05280       if ((parkinglot->cfg.parkedcallhangup == AST_FEATURE_FLAG_BYCALLER) || (parkinglot->cfg.parkedcallhangup == AST_FEATURE_FLAG_BYBOTH)) {
05281          ast_set_flag(&(config.features_caller), AST_FEATURE_DISCONNECT);
05282       }
05283       if ((parkinglot->cfg.parkedcallrecording == AST_FEATURE_FLAG_BYCALLEE) || (parkinglot->cfg.parkedcallrecording == AST_FEATURE_FLAG_BYBOTH)) {
05284          ast_set_flag(&(config.features_callee), AST_FEATURE_AUTOMON);
05285       }
05286       if ((parkinglot->cfg.parkedcallrecording == AST_FEATURE_FLAG_BYCALLER) || (parkinglot->cfg.parkedcallrecording == AST_FEATURE_FLAG_BYBOTH)) {
05287          ast_set_flag(&(config.features_caller), AST_FEATURE_AUTOMON);
05288       }
05289 
05290       res = ast_bridge_call(chan, peer, &config);
05291 
05292       pbx_builtin_setvar_helper(chan, "PARKEDCHANNEL", peer->name);
05293       ast_cdr_setdestchan(chan->cdr, peer->name);
05294 
05295       /* Simulate the PBX hanging up */
05296       ast_hangup(peer);
05297    } else {
05298       if (ast_stream_and_wait(chan, "pbx-invalidpark", "")) {
05299          ast_log(LOG_WARNING, "ast_streamfile of %s failed on %s\n", "pbx-invalidpark",
05300             chan->name);
05301       }
05302       ast_verb(3, "Channel %s tried to retrieve nonexistent parked call %d\n",
05303          chan->name, park);
05304       res = -1;
05305    }
05306 
05307    parkinglot_unref(parkinglot);
05308    return res;
05309 }
05310 
05311 /*!
05312  * \brief Unreference parkinglot object.
05313  */
05314 static void parkinglot_unref(struct ast_parkinglot *parkinglot) 
05315 {
05316    ast_debug(3, "Multiparking: %s refcount now %d\n", parkinglot->name,
05317       ao2_ref(parkinglot, 0) - 1);
05318    ao2_ref(parkinglot, -1);
05319 }
05320 
05321 static struct ast_parkinglot *parkinglot_addref(struct ast_parkinglot *parkinglot)
05322 {
05323    int refcount;
05324 
05325    refcount = ao2_ref(parkinglot, +1);
05326    ast_debug(3, "Multiparking: %s refcount now %d\n", parkinglot->name, refcount + 1);
05327    return parkinglot;
05328 }
05329 
05330 /*! \brief Destroy a parking lot */
05331 static void parkinglot_destroy(void *obj)
05332 {
05333    struct ast_parkinglot *doomed = obj;
05334 
05335    /*
05336     * No need to destroy parked calls here because any parked call
05337     * holds a parking lot reference.  Therefore the parkings list
05338     * must be empty.
05339     */
05340    ast_assert(AST_LIST_EMPTY(&doomed->parkings));
05341    AST_LIST_HEAD_DESTROY(&doomed->parkings);
05342 }
05343 
05344 /*! \brief Allocate parking lot structure */
05345 static struct ast_parkinglot *create_parkinglot(const char *name)
05346 {
05347    struct ast_parkinglot *newlot;
05348 
05349    if (ast_strlen_zero(name)) { /* No name specified */
05350       return NULL;
05351    }
05352 
05353    newlot = ao2_alloc(sizeof(*newlot), parkinglot_destroy);
05354    if (!newlot)
05355       return NULL;
05356    
05357    ast_copy_string(newlot->name, name, sizeof(newlot->name));
05358    newlot->cfg.is_invalid = 1;/* No config is set yet. */
05359    AST_LIST_HEAD_INIT(&newlot->parkings);
05360 
05361    return newlot;
05362 }
05363 
05364 /*! 
05365  * \brief Add parking hints for all defined parking spaces.
05366  * \param context Dialplan context to add the hints.
05367  * \param start Starting space in parkinglot.
05368  * \param stop Ending space in parkinglot.
05369  */
05370 static void park_add_hints(const char *context, int start, int stop)
05371 {
05372    int numext;
05373    char device[AST_MAX_EXTENSION];
05374    char exten[10];
05375 
05376    for (numext = start; numext <= stop; numext++) {
05377       snprintf(exten, sizeof(exten), "%d", numext);
05378       snprintf(device, sizeof(device), "park:%s@%s", exten, context);
05379       ast_add_extension(context, 1, exten, PRIORITY_HINT, NULL, NULL, device, NULL, NULL, registrar);
05380    }
05381 }
05382 
05383 /*! Default configuration for default parking lot. */
05384 static const struct parkinglot_cfg parkinglot_cfg_default_default = {
05385    .mohclass = "default",
05386    .parkext = DEFAULT_PARK_EXTENSION,
05387    .parking_con = "parkedcalls",
05388    .parking_start = 701,
05389    .parking_stop = 750,
05390    .parkingtime = DEFAULT_PARK_TIME,
05391 };
05392 
05393 /*! Default configuration for normal parking lots. */
05394 static const struct parkinglot_cfg parkinglot_cfg_default = {
05395    .parkext = DEFAULT_PARK_EXTENSION,
05396    .parkingtime = DEFAULT_PARK_TIME,
05397 };
05398 
05399 /*!
05400  * \internal
05401  * \brief Set parking lot feature flag configuration value.
05402  *
05403  * \param pl_name Parking lot name for diagnostic messages.
05404  * \param param Parameter value to set.
05405  * \param var Current configuration variable item.
05406  *
05407  * \return Nothing
05408  */
05409 static void parkinglot_feature_flag_cfg(const char *pl_name, int *param, struct ast_variable *var)
05410 {
05411    ast_debug(1, "Setting parking lot %s %s to %s\n", pl_name, var->name, var->value);
05412    if (!strcasecmp(var->value, "both")) {
05413       *param = AST_FEATURE_FLAG_BYBOTH;
05414    } else if (!strcasecmp(var->value, "caller")) {
05415       *param = AST_FEATURE_FLAG_BYCALLER;
05416    } else if (!strcasecmp(var->value, "callee")) {
05417       *param = AST_FEATURE_FLAG_BYCALLEE;
05418    }
05419 }
05420 
05421 /*!
05422  * \internal
05423  * \brief Read parking lot configuration.
05424  *
05425  * \param pl_name Parking lot name for diagnostic messages.
05426  * \param cfg Parking lot config to update that is already initialized with defaults.
05427  * \param var Config variable list.
05428  *
05429  * \retval 0 on success.
05430  * \retval -1 on error.
05431  */
05432 static int parkinglot_config_read(const char *pl_name, struct parkinglot_cfg *cfg, struct ast_variable *var)
05433 {
05434    int error = 0;
05435 
05436    while (var) {
05437       if (!strcasecmp(var->name, "context")) {
05438          ast_copy_string(cfg->parking_con, var->value, sizeof(cfg->parking_con));
05439       } else if (!strcasecmp(var->name, "parkext")) {
05440          ast_copy_string(cfg->parkext, var->value, sizeof(cfg->parkext));
05441       } else if (!strcasecmp(var->name, "parkext_exclusive")) {
05442          cfg->parkext_exclusive = ast_true(var->value);
05443       } else if (!strcasecmp(var->name, "parkinghints")) {
05444          cfg->parkaddhints = ast_true(var->value);
05445       } else if (!strcasecmp(var->name, "parkedmusicclass")) {
05446          ast_copy_string(cfg->mohclass, var->value, sizeof(cfg->mohclass));
05447       } else if (!strcasecmp(var->name, "parkingtime")) {
05448          int parkingtime = 0;
05449 
05450          if ((sscanf(var->value, "%30d", &parkingtime) != 1) || parkingtime < 1) {
05451             ast_log(LOG_WARNING, "%s is not a valid parkingtime\n", var->value);
05452             error = -1;
05453          } else {
05454             cfg->parkingtime = parkingtime * 1000;
05455          }
05456       } else if (!strcasecmp(var->name, "parkpos")) {
05457          int start = 0;
05458          int end = 0;
05459 
05460          if (sscanf(var->value, "%30d-%30d", &start, &end) != 2) {
05461             ast_log(LOG_WARNING,
05462                "Format for parking positions is a-b, where a and b are numbers at line %d of %s\n",
05463                var->lineno, var->file);
05464             error = -1;
05465          } else if (end < start || start <= 0 || end <= 0) {
05466             ast_log(LOG_WARNING, "Parking range is invalid. Must be a <= b, at line %d of %s\n",
05467                var->lineno, var->file);
05468             error = -1;
05469          } else {
05470             cfg->parking_start = start;
05471             cfg->parking_stop = end;
05472          }
05473       } else if (!strcasecmp(var->name, "findslot")) {
05474          cfg->parkfindnext = (!strcasecmp(var->value, "next"));
05475       } else if (!strcasecmp(var->name, "parkedcalltransfers")) {
05476          parkinglot_feature_flag_cfg(pl_name, &cfg->parkedcalltransfers, var);
05477       } else if (!strcasecmp(var->name, "parkedcallreparking")) {
05478          parkinglot_feature_flag_cfg(pl_name, &cfg->parkedcallreparking, var);
05479       } else if (!strcasecmp(var->name, "parkedcallhangup")) {
05480          parkinglot_feature_flag_cfg(pl_name, &cfg->parkedcallhangup, var);
05481       } else if (!strcasecmp(var->name, "parkedcallrecording")) {
05482          parkinglot_feature_flag_cfg(pl_name, &cfg->parkedcallrecording, var);
05483       }
05484       var = var->next;
05485    }
05486 
05487    /* Check for configuration errors */
05488    if (ast_strlen_zero(cfg->parking_con)) {
05489       ast_log(LOG_WARNING, "Parking lot %s needs context\n", pl_name);
05490       error = -1;
05491    }
05492    if (ast_strlen_zero(cfg->parkext)) {
05493       ast_log(LOG_WARNING, "Parking lot %s needs parkext\n", pl_name);
05494       error = -1;
05495    }
05496    if (!cfg->parking_start) {
05497       ast_log(LOG_WARNING, "Parking lot %s needs parkpos\n", pl_name);
05498       error = -1;
05499    }
05500    if (error) {
05501       cfg->is_invalid = 1;
05502    }
05503 
05504    return error;
05505 }
05506 
05507 /*!
05508  * \internal
05509  * \brief Activate the given parkinglot.
05510  *
05511  * \param parkinglot Parking lot to activate.
05512  *
05513  * \details
05514  * Insert into the dialplan the context, parking lot access
05515  * extension, and optional dialplan hints.
05516  *
05517  * \retval 0 on success.
05518  * \retval -1 on error.
05519  */
05520 static int parkinglot_activate(struct ast_parkinglot *parkinglot)
05521 {
05522    int disabled = 0;
05523    char app_data[5 + AST_MAX_CONTEXT];
05524 
05525    /* Create Park option list.  Must match with struct park_app_args options. */
05526    if (parkinglot->cfg.parkext_exclusive) {
05527       /* Specify the parking lot this parking extension parks calls. */
05528       snprintf(app_data, sizeof(app_data), ",,,,,%s", parkinglot->name);
05529    } else {
05530       /* The dialplan must specify which parking lot to use. */
05531       app_data[0] = '\0';
05532    }
05533 
05534    /* Create context */
05535    if (!ast_context_find_or_create(NULL, NULL, parkinglot->cfg.parking_con, registrar)) {
05536       ast_log(LOG_ERROR, "Parking context '%s' does not exist and unable to create\n",
05537          parkinglot->cfg.parking_con);
05538       disabled = 1;
05539 
05540    /* Add a parking extension into the context */
05541    } else if (ast_add_extension(parkinglot->cfg.parking_con, 1, parkinglot->cfg.parkext,
05542       1, NULL, NULL, parkcall, ast_strdup(app_data), ast_free_ptr, registrar)) {
05543       ast_log(LOG_ERROR, "Could not create parking lot %s access exten %s@%s\n",
05544          parkinglot->name, parkinglot->cfg.parkext, parkinglot->cfg.parking_con);
05545       disabled = 1;
05546    } else {
05547       /* Add parking hints */
05548       if (parkinglot->cfg.parkaddhints) {
05549          park_add_hints(parkinglot->cfg.parking_con, parkinglot->cfg.parking_start,
05550             parkinglot->cfg.parking_stop);
05551       }
05552 
05553       /*
05554        * XXX Not sure why we should need to notify the metermaids for
05555        * this exten.  It was originally done for the default parking
05556        * lot entry exten only but should be done for all entry extens
05557        * if we do it for one.
05558        */
05559       /* Notify metermaids about parking lot entry exten state. */
05560       notify_metermaids(parkinglot->cfg.parkext, parkinglot->cfg.parking_con,
05561          AST_DEVICE_INUSE);
05562    }
05563 
05564    parkinglot->disabled = disabled;
05565    return disabled ? -1 : 0;
05566 }
05567 
05568 /*! \brief Build parkinglot from configuration and chain it in if it doesn't already exist */
05569 static struct ast_parkinglot *build_parkinglot(const char *pl_name, struct ast_variable *var)
05570 {
05571    struct ast_parkinglot *parkinglot;
05572    const struct parkinglot_cfg *cfg_defaults;
05573    struct parkinglot_cfg new_cfg;
05574    int cfg_error;
05575    int oldparkinglot = 0;
05576 
05577    parkinglot = find_parkinglot(pl_name);
05578    if (parkinglot) {
05579       oldparkinglot = 1;
05580    } else {
05581       parkinglot = create_parkinglot(pl_name);
05582       if (!parkinglot) {
05583          return NULL;
05584       }
05585    }
05586    if (!strcmp(parkinglot->name, DEFAULT_PARKINGLOT)) {
05587       cfg_defaults = &parkinglot_cfg_default_default;
05588    } else {
05589       cfg_defaults = &parkinglot_cfg_default;
05590    }
05591    new_cfg = *cfg_defaults;
05592 
05593    ast_debug(1, "Building parking lot %s\n", parkinglot->name);
05594 
05595    ao2_lock(parkinglot);
05596 
05597    /* Do some config stuff */
05598    cfg_error = parkinglot_config_read(parkinglot->name, &new_cfg, var);
05599    if (oldparkinglot) {
05600       if (cfg_error) {
05601          /* Bad configuration read.  Keep using the original config. */
05602          ast_log(LOG_WARNING, "Changes to parking lot %s are discarded.\n",
05603             parkinglot->name);
05604          cfg_error = 0;
05605       } else if (!AST_LIST_EMPTY(&parkinglot->parkings)
05606          && memcmp(&new_cfg, &parkinglot->cfg, sizeof(parkinglot->cfg))) {
05607          /* Try reloading later when parking lot is empty. */
05608          ast_log(LOG_WARNING,
05609             "Parking lot %s has parked calls.  Parking lot changes discarded.\n",
05610             parkinglot->name);
05611          force_reload_load = 1;
05612       } else {
05613          /* Accept the new config */
05614          parkinglot->cfg = new_cfg;
05615       }
05616    } else {
05617       /* Load the initial parking lot config. */
05618       parkinglot->cfg = new_cfg;
05619    }
05620    parkinglot->the_mark = 0;
05621 
05622    ao2_unlock(parkinglot);
05623 
05624    if (cfg_error) {
05625       /* Only new parking lots could have config errors here. */
05626       ast_log(LOG_WARNING, "New parking lot %s is discarded.\n", parkinglot->name);
05627       parkinglot_unref(parkinglot);
05628       return NULL;
05629    }
05630 
05631    /* Move it into the list, if it wasn't already there */
05632    if (!oldparkinglot) {
05633       ao2_link(parkinglots, parkinglot);
05634    }
05635    parkinglot_unref(parkinglot);
05636 
05637    return parkinglot;
05638 }
05639 
05640 /*!
05641  * \internal
05642  * \brief Process an applicationmap section config line.
05643  *
05644  * \param var Config variable line.
05645  *
05646  * \return Nothing
05647  */
05648 static void process_applicationmap_line(struct ast_variable *var)
05649 {
05650    char *tmp_val = ast_strdupa(var->value);
05651    char *activateon, *new_syn;
05652    struct ast_call_feature *feature;
05653    AST_DECLARE_APP_ARGS(args,
05654       AST_APP_ARG(exten);
05655       AST_APP_ARG(activatedby);
05656       AST_APP_ARG(app);
05657       AST_APP_ARG(app_args);
05658       AST_APP_ARG(moh_class);
05659    );
05660 
05661    AST_STANDARD_APP_ARGS(args, tmp_val);
05662    if ((new_syn = strchr(args.app, '('))) {
05663       /* New syntax */
05664       args.moh_class = args.app_args;
05665       args.app_args = new_syn;
05666       *args.app_args++ = '\0';
05667       if (args.app_args[strlen(args.app_args) - 1] == ')') {
05668          args.app_args[strlen(args.app_args) - 1] = '\0';
05669       }
05670    }
05671 
05672    activateon = strsep(&args.activatedby, "/");
05673 
05674    /*! \todo XXX var_name or app_args ? */
05675    if (ast_strlen_zero(args.app)
05676       || ast_strlen_zero(args.exten)
05677       || ast_strlen_zero(activateon)
05678       || ast_strlen_zero(var->name)) {
05679       ast_log(LOG_NOTICE,
05680          "Please check the feature Mapping Syntax, either extension, name, or app aren't provided %s %s %s %s\n",
05681          args.app, args.exten, activateon, var->name);
05682       return;
05683    }
05684 
05685    AST_RWLIST_RDLOCK(&feature_list);
05686    if (find_dynamic_feature(var->name)) {
05687       AST_RWLIST_UNLOCK(&feature_list);
05688       ast_log(LOG_WARNING, "Dynamic Feature '%s' specified more than once!\n",
05689          var->name);
05690       return;
05691    }
05692    AST_RWLIST_UNLOCK(&feature_list);
05693 
05694    if (!(feature = ast_calloc(1, sizeof(*feature)))) {
05695       return;
05696    }
05697 
05698    ast_copy_string(feature->sname, var->name, FEATURE_SNAME_LEN);
05699    ast_copy_string(feature->app, args.app, FEATURE_APP_LEN);
05700    ast_copy_string(feature->exten, args.exten, FEATURE_EXTEN_LEN);
05701 
05702    if (args.app_args) {
05703       ast_copy_string(feature->app_args, args.app_args, FEATURE_APP_ARGS_LEN);
05704    }
05705 
05706    if (args.moh_class) {
05707       ast_copy_string(feature->moh_class, args.moh_class, FEATURE_MOH_LEN);
05708    }
05709 
05710    ast_copy_string(feature->exten, args.exten, sizeof(feature->exten));
05711    feature->operation = feature_exec_app;
05712    ast_set_flag(feature, AST_FEATURE_FLAG_NEEDSDTMF);
05713 
05714    /* Allow caller and callee to be specified for backwards compatability */
05715    if (!strcasecmp(activateon, "self") || !strcasecmp(activateon, "caller")) {
05716       ast_set_flag(feature, AST_FEATURE_FLAG_ONSELF);
05717    } else if (!strcasecmp(activateon, "peer") || !strcasecmp(activateon, "callee")) {
05718       ast_set_flag(feature, AST_FEATURE_FLAG_ONPEER);
05719    } else {
05720       ast_log(LOG_NOTICE, "Invalid 'ActivateOn' specification for feature '%s',"
05721          " must be 'self', or 'peer'\n", var->name);
05722       ast_free(feature);
05723       return;
05724    }
05725 
05726    if (ast_strlen_zero(args.activatedby)) {
05727       ast_set_flag(feature, AST_FEATURE_FLAG_BYBOTH);
05728    } else if (!strcasecmp(args.activatedby, "caller")) {
05729       ast_set_flag(feature, AST_FEATURE_FLAG_BYCALLER);
05730    } else if (!strcasecmp(args.activatedby, "callee")) {
05731       ast_set_flag(feature, AST_FEATURE_FLAG_BYCALLEE);
05732    } else if (!strcasecmp(args.activatedby, "both")) {
05733       ast_set_flag(feature, AST_FEATURE_FLAG_BYBOTH);
05734    } else {
05735       ast_log(LOG_NOTICE, "Invalid 'ActivatedBy' specification for feature '%s',"
05736          " must be 'caller', or 'callee', or 'both'\n", var->name);
05737       ast_free(feature);
05738       return;
05739    }
05740 
05741    ast_register_feature(feature);
05742 
05743    ast_verb(2, "Mapping Feature '%s' to app '%s(%s)' with code '%s'\n",
05744       var->name, args.app, args.app_args, args.exten);
05745 }
05746 
05747 static int process_config(struct ast_config *cfg)
05748 {
05749    int i;
05750    struct ast_variable *var = NULL;
05751    struct feature_group *fg = NULL;
05752    char *ctg; 
05753    static const char * const categories[] = { 
05754       /* Categories in features.conf that are not
05755        * to be parsed as group categories
05756        */
05757       "general",
05758       "featuremap",
05759       "applicationmap"
05760    };
05761 
05762    /* Set general features global defaults. */
05763    featuredigittimeout = DEFAULT_FEATURE_DIGIT_TIMEOUT;
05764 
05765    /* Set global call pickup defaults. */
05766    strcpy(pickup_ext, "*8");
05767    pickupsound[0] = '\0';
05768    pickupfailsound[0] = '\0';
05769 
05770    /* Set global call transfer defaults. */
05771    strcpy(xfersound, "beep");
05772    strcpy(xferfailsound, "beeperr");
05773    transferdigittimeout = DEFAULT_TRANSFER_DIGIT_TIMEOUT;
05774    atxfernoanswertimeout = DEFAULT_NOANSWER_TIMEOUT_ATTENDED_TRANSFER;
05775    atxferloopdelay = DEFAULT_ATXFER_LOOP_DELAY;
05776    atxferdropcall = DEFAULT_ATXFER_DROP_CALL;
05777    atxfercallbackretries = DEFAULT_ATXFER_CALLBACK_RETRIES;
05778 
05779    /* Set global call parking defaults. */
05780    comebacktoorigin = 1;
05781    courtesytone[0] = '\0';
05782    parkedplay = 0;
05783    adsipark = 0;
05784    parkeddynamic = 0;
05785 
05786    var = ast_variable_browse(cfg, "general");
05787    build_parkinglot(DEFAULT_PARKINGLOT, var);
05788    for (; var; var = var->next) {
05789       if (!strcasecmp(var->name, "parkeddynamic")) {
05790          parkeddynamic = ast_true(var->value);
05791       } else if (!strcasecmp(var->name, "adsipark")) {
05792          adsipark = ast_true(var->value);
05793       } else if (!strcasecmp(var->name, "transferdigittimeout")) {
05794          if ((sscanf(var->value, "%30d", &transferdigittimeout) != 1) || (transferdigittimeout < 1)) {
05795             ast_log(LOG_WARNING, "%s is not a valid transferdigittimeout\n", var->value);
05796             transferdigittimeout = DEFAULT_TRANSFER_DIGIT_TIMEOUT;
05797          } else {
05798             transferdigittimeout = transferdigittimeout * 1000;
05799          }
05800       } else if (!strcasecmp(var->name, "featuredigittimeout")) {
05801          if ((sscanf(var->value, "%30d", &featuredigittimeout) != 1) || (featuredigittimeout < 1)) {
05802             ast_log(LOG_WARNING, "%s is not a valid featuredigittimeout\n", var->value);
05803             featuredigittimeout = DEFAULT_FEATURE_DIGIT_TIMEOUT;
05804          }
05805       } else if (!strcasecmp(var->name, "atxfernoanswertimeout")) {
05806          if ((sscanf(var->value, "%30d", &atxfernoanswertimeout) != 1) || (atxfernoanswertimeout < 1)) {
05807             ast_log(LOG_WARNING, "%s is not a valid atxfernoanswertimeout\n", var->value);
05808             atxfernoanswertimeout = DEFAULT_NOANSWER_TIMEOUT_ATTENDED_TRANSFER;
05809          } else {
05810             atxfernoanswertimeout = atxfernoanswertimeout * 1000;
05811          }
05812       } else if (!strcasecmp(var->name, "atxferloopdelay")) {
05813          if ((sscanf(var->value, "%30u", &atxferloopdelay) != 1)) {
05814             ast_log(LOG_WARNING, "%s is not a valid atxferloopdelay\n", var->value);
05815             atxferloopdelay = DEFAULT_ATXFER_LOOP_DELAY;
05816          } else {
05817             atxferloopdelay *= 1000;
05818          }
05819       } else if (!strcasecmp(var->name, "atxferdropcall")) {
05820          atxferdropcall = ast_true(var->value);
05821       } else if (!strcasecmp(var->name, "atxfercallbackretries")) {
05822          if ((sscanf(var->value, "%30u", &atxfercallbackretries) != 1)) {
05823             ast_log(LOG_WARNING, "%s is not a valid atxfercallbackretries\n", var->value);
05824             atxfercallbackretries = DEFAULT_ATXFER_CALLBACK_RETRIES;
05825          }
05826       } else if (!strcasecmp(var->name, "courtesytone")) {
05827          ast_copy_string(courtesytone, var->value, sizeof(courtesytone));
05828       }  else if (!strcasecmp(var->name, "parkedplay")) {
05829          if (!strcasecmp(var->value, "both")) {
05830             parkedplay = 2;
05831          } else if (!strcasecmp(var->value, "parked")) {
05832             parkedplay = 1;
05833          } else {
05834             parkedplay = 0;
05835          }
05836       } else if (!strcasecmp(var->name, "xfersound")) {
05837          ast_copy_string(xfersound, var->value, sizeof(xfersound));
05838       } else if (!strcasecmp(var->name, "xferfailsound")) {
05839          ast_copy_string(xferfailsound, var->value, sizeof(xferfailsound));
05840       } else if (!strcasecmp(var->name, "pickupexten")) {
05841          ast_copy_string(pickup_ext, var->value, sizeof(pickup_ext));
05842       } else if (!strcasecmp(var->name, "pickupsound")) {
05843          ast_copy_string(pickupsound, var->value, sizeof(pickupsound));
05844       } else if (!strcasecmp(var->name, "pickupfailsound")) {
05845          ast_copy_string(pickupfailsound, var->value, sizeof(pickupfailsound));
05846       } else if (!strcasecmp(var->name, "comebacktoorigin")) {
05847          comebacktoorigin = ast_true(var->value);
05848       }
05849    }
05850 
05851    unmap_features();
05852    for (var = ast_variable_browse(cfg, "featuremap"); var; var = var->next) {
05853       if (remap_feature(var->name, var->value)) {
05854          ast_log(LOG_NOTICE, "Unknown feature '%s'\n", var->name);
05855       }
05856    }
05857 
05858    /* Map a key combination to an application */
05859    ast_unregister_features();
05860    for (var = ast_variable_browse(cfg, "applicationmap"); var; var = var->next) {
05861       process_applicationmap_line(var);
05862    }
05863 
05864    ast_unregister_groups();
05865    AST_RWLIST_WRLOCK(&feature_groups);
05866 
05867    ctg = NULL;
05868    while ((ctg = ast_category_browse(cfg, ctg))) {
05869       /* Is this a parkinglot definition ? */
05870       if (!strncasecmp(ctg, "parkinglot_", strlen("parkinglot_"))) {
05871          ast_debug(2, "Found configuration section %s, assume parking context\n", ctg);
05872          if (!build_parkinglot(ctg, ast_variable_browse(cfg, ctg))) {
05873             ast_log(LOG_ERROR, "Could not build parking lot %s. Configuration error.\n", ctg);
05874          } else {
05875             ast_debug(1, "Configured parking context %s\n", ctg);
05876          }
05877          continue;   
05878       }
05879 
05880       /* No, check if it's a group */
05881       for (i = 0; i < ARRAY_LEN(categories); i++) {
05882          if (!strcasecmp(categories[i], ctg)) {
05883             break;
05884          }
05885       }
05886       if (i < ARRAY_LEN(categories)) {
05887          continue;
05888       }
05889 
05890       if (!(fg = register_group(ctg))) {
05891          continue;
05892       }
05893 
05894       for (var = ast_variable_browse(cfg, ctg); var; var = var->next) {
05895          struct ast_call_feature *feature;
05896 
05897          AST_RWLIST_RDLOCK(&feature_list);
05898          if (!(feature = find_dynamic_feature(var->name)) && 
05899              !(feature = ast_find_call_feature(var->name))) {
05900             AST_RWLIST_UNLOCK(&feature_list);
05901             ast_log(LOG_WARNING, "Feature '%s' was not found.\n", var->name);
05902             continue;
05903          }
05904          AST_RWLIST_UNLOCK(&feature_list);
05905 
05906          register_group_feature(fg, var->value, feature);
05907       }
05908    }
05909 
05910    AST_RWLIST_UNLOCK(&feature_groups);
05911 
05912    return 0;
05913 }
05914 
05915 /*!
05916  * \internal
05917  * \brief Destroy the given dialplan usage context.
05918  *
05919  * \param doomed Parking lot usage context to destroy.
05920  *
05921  * \return Nothing
05922  */
05923 static void destroy_dialplan_usage_context(struct parking_dp_context *doomed)
05924 {
05925    struct parking_dp_ramp *ramp;
05926    struct parking_dp_spaces *spaces;
05927 
05928    while ((ramp = AST_LIST_REMOVE_HEAD(&doomed->access_extens, node))) {
05929       ast_free(ramp);
05930    }
05931    while ((spaces = AST_LIST_REMOVE_HEAD(&doomed->spaces, node))) {
05932       ast_free(spaces);
05933    }
05934    while ((spaces = AST_LIST_REMOVE_HEAD(&doomed->hints, node))) {
05935       ast_free(spaces);
05936    }
05937    ast_free(doomed);
05938 }
05939 
05940 /*!
05941  * \internal
05942  * \brief Destroy the given dialplan usage map.
05943  *
05944  * \param doomed Parking lot usage map to destroy.
05945  *
05946  * \return Nothing
05947  */
05948 static void destroy_dialplan_usage_map(struct parking_dp_map *doomed)
05949 {
05950    struct parking_dp_context *item;
05951 
05952    while ((item = AST_LIST_REMOVE_HEAD(doomed, node))) {
05953       destroy_dialplan_usage_context(item);
05954    }
05955 }
05956 
05957 /*!
05958  * \internal
05959  * \brief Create a new parking lot ramp dialplan usage node.
05960  *
05961  * \param exten Parking lot access ramp extension.
05962  * \param exclusive TRUE if the parking lot access ramp extension is exclusive.
05963  *
05964  * \retval New usage ramp node on success.
05965  * \retval NULL on error.
05966  */
05967 static struct parking_dp_ramp *build_dialplan_useage_ramp(const char *exten, int exclusive)
05968 {
05969    struct parking_dp_ramp *ramp_node;
05970 
05971    ramp_node = ast_calloc(1, sizeof(*ramp_node) + strlen(exten));
05972    if (!ramp_node) {
05973       return NULL;
05974    }
05975    ramp_node->exclusive = exclusive;
05976    strcpy(ramp_node->exten, exten);
05977    return ramp_node;
05978 }
05979 
05980 /*!
05981  * \internal
05982  * \brief Add parking lot access ramp to the context ramp usage map.
05983  *
05984  * \param ramp_map Current parking lot context ramp usage map.
05985  * \param exten Parking lot access ramp extension to add.
05986  * \param exclusive TRUE if the parking lot access ramp extension is exclusive.
05987  * \param lot Parking lot supplying reference data.
05988  * \param complain TRUE if to complain of parking lot ramp conflicts.
05989  *
05990  * \retval 0 on success.  The ramp_map is updated.
05991  * \retval -1 on failure.
05992  */
05993 static int usage_context_add_ramp(struct parking_dp_ramp_map *ramp_map, const char *exten, int exclusive, struct ast_parkinglot *lot, int complain)
05994 {
05995    struct parking_dp_ramp *cur_ramp;
05996    struct parking_dp_ramp *new_ramp;
05997    int cmp;
05998 
05999    /* Make sure that exclusive is only 0 or 1 */
06000    if (exclusive) {
06001       exclusive = 1;
06002    }
06003 
06004    AST_LIST_TRAVERSE_SAFE_BEGIN(ramp_map, cur_ramp, node) {
06005       cmp = strcmp(exten, cur_ramp->exten);
06006       if (cmp > 0) {
06007          /* The parking lot ramp goes after this node. */
06008          continue;
06009       }
06010       if (cmp == 0) {
06011          /* The ramp is already in the map. */
06012          if (complain && (cur_ramp->exclusive || exclusive)) {
06013             ast_log(LOG_WARNING,
06014                "Parking lot '%s' parkext %s@%s used by another parking lot.\n",
06015                lot->name, exten, lot->cfg.parking_con);
06016          }
06017          return 0;
06018       }
06019       /* The new parking lot ramp goes before this node. */
06020       new_ramp = build_dialplan_useage_ramp(exten, exclusive);
06021       if (!new_ramp) {
06022          return -1;
06023       }
06024       AST_LIST_INSERT_BEFORE_CURRENT(new_ramp, node);
06025       return 0;
06026    }
06027    AST_LIST_TRAVERSE_SAFE_END;
06028 
06029    /* New parking lot access ramp goes on the end. */
06030    new_ramp = build_dialplan_useage_ramp(exten, exclusive);
06031    if (!new_ramp) {
06032       return -1;
06033    }
06034    AST_LIST_INSERT_TAIL(ramp_map, new_ramp, node);
06035    return 0;
06036 }
06037 
06038 /*!
06039  * \internal
06040  * \brief Create a new parking lot spaces dialplan usage node.
06041  *
06042  * \param start First parking lot space to add.
06043  * \param stop Last parking lot space to add.
06044  *
06045  * \retval New usage ramp node on success.
06046  * \retval NULL on error.
06047  */
06048 static struct parking_dp_spaces *build_dialplan_useage_spaces(int start, int stop)
06049 {
06050    struct parking_dp_spaces *spaces_node;
06051 
06052    spaces_node = ast_calloc(1, sizeof(*spaces_node));
06053    if (!spaces_node) {
06054       return NULL;
06055    }
06056    spaces_node->start = start;
06057    spaces_node->stop = stop;
06058    return spaces_node;
06059 }
06060 
06061 /*!
06062  * \internal
06063  * \brief Add parking lot spaces to the context space usage map.
06064  *
06065  * \param space_map Current parking lot context space usage map.
06066  * \param start First parking lot space to add.
06067  * \param stop Last parking lot space to add.
06068  * \param lot Parking lot supplying reference data.
06069  * \param complain TRUE if to complain of parking lot spaces conflicts.
06070  *
06071  * \retval 0 on success.  The space_map is updated.
06072  * \retval -1 on failure.
06073  */
06074 static int usage_context_add_spaces(struct parking_dp_space_map *space_map, int start, int stop, struct ast_parkinglot *lot, int complain)
06075 {
06076    struct parking_dp_spaces *cur_node;
06077    struct parking_dp_spaces *expand_node;
06078    struct parking_dp_spaces *new_node;
06079 
06080    expand_node = NULL;
06081    AST_LIST_TRAVERSE_SAFE_BEGIN(space_map, cur_node, node) {
06082       /* NOTE: stop + 1 to combine immediately adjacent nodes into one. */
06083       if (expand_node) {
06084          /* The previous node is expanding to possibly eat following nodes. */
06085          if (expand_node->stop + 1 < cur_node->start) {
06086             /* Current node is completely after expanding node. */
06087             return 0;
06088          }
06089 
06090          if (complain
06091             && ((cur_node->start <= start && start <= cur_node->stop)
06092                || (cur_node->start <= stop && stop <= cur_node->stop)
06093                || (start < cur_node->start && cur_node->stop < stop))) {
06094             /* Only complain once per range add. */
06095             complain = 0;
06096             ast_log(LOG_WARNING,
06097                "Parking lot '%s' parkpos %d-%d@%s overlaps another parking lot.\n",
06098                lot->name, start, stop, lot->cfg.parking_con);
06099          }
06100 
06101          /* Current node is eaten by the expanding node. */
06102          if (expand_node->stop < cur_node->stop) {
06103             expand_node->stop = cur_node->stop;
06104          }
06105          AST_LIST_REMOVE_CURRENT(node);
06106          ast_free(cur_node);
06107          continue;
06108       }
06109 
06110       if (cur_node->stop + 1 < start) {
06111          /* New range is completely after current node. */
06112          continue;
06113       }
06114       if (stop + 1 < cur_node->start) {
06115          /* New range is completely before current node. */
06116          new_node = build_dialplan_useage_spaces(start, stop);
06117          if (!new_node) {
06118             return -1;
06119          }
06120          AST_LIST_INSERT_BEFORE_CURRENT(new_node, node);
06121          return 0;
06122       }
06123 
06124       if (complain
06125          && ((cur_node->start <= start && start <= cur_node->stop)
06126             || (cur_node->start <= stop && stop <= cur_node->stop)
06127             || (start < cur_node->start && cur_node->stop < stop))) {
06128          /* Only complain once per range add. */
06129          complain = 0;
06130          ast_log(LOG_WARNING,
06131             "Parking lot '%s' parkpos %d-%d@%s overlaps another parking lot.\n",
06132             lot->name, start, stop, lot->cfg.parking_con);
06133       }
06134 
06135       /* Current node range overlaps or is immediately adjacent to new range. */
06136       if (start < cur_node->start) {
06137          /* Expand the current node in the front. */
06138          cur_node->start = start;
06139       }
06140       if (stop <= cur_node->stop) {
06141          /* Current node is not expanding in the rear. */
06142          return 0;
06143       }
06144       cur_node->stop = stop;
06145       expand_node = cur_node;
06146    }
06147    AST_LIST_TRAVERSE_SAFE_END;
06148 
06149    if (expand_node) {
06150       /*
06151        * The previous node expanded and either ate all following nodes
06152        * or it was the last node.
06153        */
06154       return 0;
06155    }
06156 
06157    /* New range goes on the end. */
06158    new_node = build_dialplan_useage_spaces(start, stop);
06159    if (!new_node) {
06160       return -1;
06161    }
06162    AST_LIST_INSERT_TAIL(space_map, new_node, node);
06163    return 0;
06164 }
06165 
06166 /*!
06167  * \internal
06168  * \brief Add parking lot spaces to the context dialplan usage node.
06169  *
06170  * \param ctx_node Usage node to add parking lot spaces.
06171  * \param lot Parking lot to add data to ctx_node.
06172  * \param complain TRUE if to complain of parking lot ramp and spaces conflicts.
06173  *
06174  * \retval 0 on success.
06175  * \retval -1 on error.
06176  */
06177 static int dialplan_usage_add_parkinglot_data(struct parking_dp_context *ctx_node, struct ast_parkinglot *lot, int complain)
06178 {
06179    if (usage_context_add_ramp(&ctx_node->access_extens, lot->cfg.parkext,
06180       lot->cfg.parkext_exclusive, lot, complain)) {
06181       return -1;
06182    }
06183    if (usage_context_add_spaces(&ctx_node->spaces, lot->cfg.parking_start,
06184       lot->cfg.parking_stop, lot, complain)) {
06185       return -1;
06186    }
06187    if (lot->cfg.parkaddhints
06188       && usage_context_add_spaces(&ctx_node->hints, lot->cfg.parking_start,
06189          lot->cfg.parking_stop, lot, 0)) {
06190       return -1;
06191    }
06192    return 0;
06193 }
06194 
06195 /*!
06196  * \internal
06197  * \brief Create a new parking lot context dialplan usage node.
06198  *
06199  * \param lot Parking lot to create a new dialplan usage from.
06200  *
06201  * \retval New usage context node on success.
06202  * \retval NULL on error.
06203  */
06204 static struct parking_dp_context *build_dialplan_useage_context(struct ast_parkinglot *lot)
06205 {
06206    struct parking_dp_context *ctx_node;
06207 
06208    ctx_node = ast_calloc(1, sizeof(*ctx_node) + strlen(lot->cfg.parking_con));
06209    if (!ctx_node) {
06210       return NULL;
06211    }
06212    if (dialplan_usage_add_parkinglot_data(ctx_node, lot, 0)) {
06213       destroy_dialplan_usage_context(ctx_node);
06214       return NULL;
06215    }
06216    strcpy(ctx_node->context, lot->cfg.parking_con);
06217    return ctx_node;
06218 }
06219 
06220 /*!
06221  * \internal
06222  * \brief Add the given parking lot dialplan usage to the dialplan usage map.
06223  *
06224  * \param usage_map Parking lot usage map to add the given parking lot.
06225  * \param lot Parking lot to add dialplan usage.
06226  * \param complain TRUE if to complain of parking lot ramp and spaces conflicts.
06227  *
06228  * \retval 0 on success.
06229  * \retval -1 on error.
06230  */
06231 static int dialplan_usage_add_parkinglot(struct parking_dp_map *usage_map, struct ast_parkinglot *lot, int complain)
06232 {
06233    struct parking_dp_context *cur_ctx;
06234    struct parking_dp_context *new_ctx;
06235    int cmp;
06236 
06237    AST_LIST_TRAVERSE_SAFE_BEGIN(usage_map, cur_ctx, node) {
06238       cmp = strcmp(lot->cfg.parking_con, cur_ctx->context);
06239       if (cmp > 0) {
06240          /* The parking lot context goes after this node. */
06241          continue;
06242       }
06243       if (cmp == 0) {
06244          /* This is the node we will add parking lot spaces to the map. */
06245          return dialplan_usage_add_parkinglot_data(cur_ctx, lot, complain);
06246       }
06247       /* The new parking lot context goes before this node. */
06248       new_ctx = build_dialplan_useage_context(lot);
06249       if (!new_ctx) {
06250          return -1;
06251       }
06252       AST_LIST_INSERT_BEFORE_CURRENT(new_ctx, node);
06253       return 0;
06254    }
06255    AST_LIST_TRAVERSE_SAFE_END;
06256 
06257    /* New parking lot context goes on the end. */
06258    new_ctx = build_dialplan_useage_context(lot);
06259    if (!new_ctx) {
06260       return -1;
06261    }
06262    AST_LIST_INSERT_TAIL(usage_map, new_ctx, node);
06263    return 0;
06264 }
06265 
06266 /*!
06267  * \internal
06268  * \brief Build the dialplan usage map of the current parking lot container.
06269  *
06270  * \param usage_map Parking lot usage map.  Must already be initialized.
06271  * \param complain TRUE if to complain of parking lot ramp and spaces conflicts.
06272  *
06273  * \retval 0 on success.  The usage_map is filled in.
06274  * \retval -1 on failure.  Built usage_map is incomplete.
06275  */
06276 static int build_dialplan_useage_map(struct parking_dp_map *usage_map, int complain)
06277 {
06278    int status = 0;
06279    struct ao2_iterator iter;
06280    struct ast_parkinglot *curlot;
06281 
06282    /* For all parking lots */
06283    iter = ao2_iterator_init(parkinglots, 0);
06284    for (; (curlot = ao2_iterator_next(&iter)); ao2_ref(curlot, -1)) {
06285       /* Add the parking lot to the map. */
06286       if (dialplan_usage_add_parkinglot(usage_map, curlot, complain)) {
06287          ao2_ref(curlot, -1);
06288          status = -1;
06289          break;
06290       }
06291    }
06292    ao2_iterator_destroy(&iter);
06293 
06294    return status;
06295 }
06296 
06297 /*!
06298  * \internal
06299  * \brief Remove the given extension if it exists.
06300  *
06301  * \param context Dialplan database context name.
06302  * \param exten Extension to remove.
06303  * \param priority Extension priority to remove.
06304  *
06305  * \return Nothing
06306  */
06307 static void remove_exten_if_exist(const char *context, const char *exten, int priority)
06308 {
06309    struct pbx_find_info q = { .stacklen = 0 }; /* the rest is reset in pbx_find_extension */
06310 
06311    if (pbx_find_extension(NULL, NULL, &q, context, exten, priority, NULL, NULL,
06312       E_MATCH)) {
06313       ast_debug(1, "Removing unneeded parking lot exten: %s@%s priority:%d\n",
06314          context, exten, priority);
06315       ast_context_remove_extension(context, exten, priority, registrar);
06316    }
06317 }
06318 
06319 /*!
06320  * \internal
06321  * \brief Remove unused parking lot access ramp items.
06322  *
06323  * \param context Dialplan database context name.
06324  * \param old_ramps Before configuration reload access ramp usage map.
06325  * \param new_ramps After configuration reload access ramp usage map.
06326  *
06327  * \details
06328  * Remove access ramp items that were in the old context but not in the
06329  * new context.
06330  *
06331  * \return Nothing
06332  */
06333 static void remove_dead_ramp_usage(const char *context, struct parking_dp_ramp_map *old_ramps, struct parking_dp_ramp_map *new_ramps)
06334 {
06335    struct parking_dp_ramp *old_ramp;
06336    struct parking_dp_ramp *new_ramp;
06337    int cmp;
06338 
06339    old_ramp = AST_LIST_FIRST(old_ramps);
06340    new_ramp = AST_LIST_FIRST(new_ramps);
06341 
06342    while (new_ramp) {
06343       if (!old_ramp) {
06344          /* No old ramps left, so no dead ramps can remain. */
06345          return;
06346       }
06347       cmp = strcmp(old_ramp->exten, new_ramp->exten);
06348       if (cmp < 0) {
06349          /* New map does not have old ramp. */
06350          remove_exten_if_exist(context, old_ramp->exten, 1);
06351          old_ramp = AST_LIST_NEXT(old_ramp, node);
06352          continue;
06353       }
06354       if (cmp == 0) {
06355          /* Old and new map have this ramp. */
06356          old_ramp = AST_LIST_NEXT(old_ramp, node);
06357       } else {
06358          /* Old map does not have new ramp. */
06359       }
06360       new_ramp = AST_LIST_NEXT(new_ramp, node);
06361    }
06362 
06363    /* Any old ramps left must be dead. */
06364    for (; old_ramp; old_ramp = AST_LIST_NEXT(old_ramp, node)) {
06365       remove_exten_if_exist(context, old_ramp->exten, 1);
06366    }
06367 }
06368 
06369 /*!
06370  * \internal
06371  * \brief Destroy the given parking space.
06372  *
06373  * \param context Dialplan database context name.
06374  * \param space Parking space.
06375  *
06376  * \return Nothing
06377  */
06378 static void destroy_space(const char *context, int space)
06379 {
06380    char exten[AST_MAX_EXTENSION];
06381 
06382    /* Destroy priorities of the parking space that we registered. */
06383    snprintf(exten, sizeof(exten), "%d", space);
06384    remove_exten_if_exist(context, exten, PRIORITY_HINT);
06385    remove_exten_if_exist(context, exten, 1);
06386 }
06387 
06388 /*!
06389  * \internal
06390  * \brief Remove unused parking lot space items.
06391  *
06392  * \param context Dialplan database context name.
06393  * \param old_spaces Before configuration reload parking space usage map.
06394  * \param new_spaces After configuration reload parking space usage map.
06395  * \param destroy_space Function to destroy parking space item.
06396  *
06397  * \details
06398  * Remove parking space items that were in the old context but
06399  * not in the new context.
06400  *
06401  * \return Nothing
06402  */
06403 static void remove_dead_spaces_usage(const char *context,
06404    struct parking_dp_space_map *old_spaces, struct parking_dp_space_map *new_spaces,
06405    void (*destroy_space)(const char *context, int space))
06406 {
06407    struct parking_dp_spaces *old_range;
06408    struct parking_dp_spaces *new_range;
06409    int space;/*!< Current position in the current old range. */
06410    int stop;
06411 
06412    old_range = AST_LIST_FIRST(old_spaces);
06413    new_range = AST_LIST_FIRST(new_spaces);
06414    space = -1;
06415 
06416    while (old_range) {
06417       if (space < old_range->start) {
06418          space = old_range->start;
06419       }
06420       if (new_range) {
06421          if (space < new_range->start) {
06422             /* Current position in old range starts before new range. */
06423             if (old_range->stop < new_range->start) {
06424                /* Old range ends before new range. */
06425                stop = old_range->stop;
06426                old_range = AST_LIST_NEXT(old_range, node);
06427             } else {
06428                /* Tail of old range overlaps new range. */
06429                stop = new_range->start - 1;
06430             }
06431          } else if (/* new_range->start <= space && */ space <= new_range->stop) {
06432             /* Current position in old range overlaps new range. */
06433             if (old_range->stop <= new_range->stop) {
06434                /* Old range ends at or before new range. */
06435                old_range = AST_LIST_NEXT(old_range, node);
06436             } else {
06437                /* Old range extends beyond end of new range. */
06438                space = new_range->stop + 1;
06439                new_range = AST_LIST_NEXT(new_range, node);
06440             }
06441             continue;
06442          } else /* if (new_range->stop < space) */ {
06443             /* Current position in old range starts after new range. */
06444             new_range = AST_LIST_NEXT(new_range, node);
06445             continue;
06446          }
06447       } else {
06448          /* No more new ranges.  All remaining old spaces are dead. */
06449          stop = old_range->stop;
06450          old_range = AST_LIST_NEXT(old_range, node);
06451       }
06452 
06453       /* Destroy dead parking spaces. */
06454       for (; space <= stop; ++space) {
06455          destroy_space(context, space);
06456       }
06457    }
06458 }
06459 
06460 /*!
06461  * \internal
06462  * \brief Remove unused parking lot context items.
06463  *
06464  * \param context Dialplan database context name.
06465  * \param old_ctx Before configuration reload context usage map.
06466  * \param new_ctx After configuration reload context usage map.
06467  *
06468  * \details
06469  * Remove context usage items that were in the old context but not in the
06470  * new context.
06471  *
06472  * \return Nothing
06473  */
06474 static void remove_dead_context_usage(const char *context, struct parking_dp_context *old_ctx, struct parking_dp_context *new_ctx)
06475 {
06476    remove_dead_ramp_usage(context, &old_ctx->access_extens, &new_ctx->access_extens);
06477    remove_dead_spaces_usage(context, &old_ctx->spaces, &new_ctx->spaces, destroy_space);
06478 #if 0
06479    /* I don't think we should destroy hints if the parking space still exists. */
06480    remove_dead_spaces_usage(context, &old_ctx->hints, &new_ctx->hints, destroy_space_hint);
06481 #endif
06482 }
06483 
06484 /*!
06485  * \internal
06486  * \brief Remove unused parking lot dialplan items.
06487  *
06488  * \param old_map Before configuration reload dialplan usage map.
06489  * \param new_map After configuration reload dialplan usage map.
06490  *
06491  * \details
06492  * Remove dialplan items that were in the old map but not in the
06493  * new map.
06494  *
06495  * \return Nothing
06496  */
06497 static void remove_dead_dialplan_useage(struct parking_dp_map *old_map, struct parking_dp_map *new_map)
06498 {
06499    struct parking_dp_context *old_ctx;
06500    struct parking_dp_context *new_ctx;
06501    struct ast_context *con;
06502    int cmp;
06503 
06504    old_ctx = AST_LIST_FIRST(old_map);
06505    new_ctx = AST_LIST_FIRST(new_map);
06506 
06507    while (new_ctx) {
06508       if (!old_ctx) {
06509          /* No old contexts left, so no dead stuff can remain. */
06510          return;
06511       }
06512       cmp = strcmp(old_ctx->context, new_ctx->context);
06513       if (cmp < 0) {
06514          /* New map does not have old map context. */
06515          con = ast_context_find(old_ctx->context);
06516          if (con) {
06517             ast_context_destroy(con, registrar);
06518          }
06519          old_ctx = AST_LIST_NEXT(old_ctx, node);
06520          continue;
06521       }
06522       if (cmp == 0) {
06523          /* Old and new map have this context. */
06524          remove_dead_context_usage(old_ctx->context, old_ctx, new_ctx);
06525          old_ctx = AST_LIST_NEXT(old_ctx, node);
06526       } else {
06527          /* Old map does not have new map context. */
06528       }
06529       new_ctx = AST_LIST_NEXT(new_ctx, node);
06530    }
06531 
06532    /* Any old contexts left must be dead. */
06533    for (; old_ctx; old_ctx = AST_LIST_NEXT(old_ctx, node)) {
06534       con = ast_context_find(old_ctx->context);
06535       if (con) {
06536          ast_context_destroy(con, registrar);
06537       }
06538    }
06539 }
06540 
06541 static int parkinglot_markall_cb(void *obj, void *arg, int flags)
06542 {
06543    struct ast_parkinglot *parkinglot = obj;
06544 
06545    parkinglot->the_mark = 1;
06546    return 0;
06547 }
06548 
06549 static int parkinglot_is_marked_cb(void *obj, void *arg, int flags)
06550 {
06551    struct ast_parkinglot *parkinglot = obj;
06552 
06553    if (parkinglot->the_mark) {
06554       if (AST_LIST_EMPTY(&parkinglot->parkings)) {
06555          /* This parking lot can actually be deleted. */
06556          return CMP_MATCH;
06557       }
06558       /* Try reloading later when parking lot is empty. */
06559       ast_log(LOG_WARNING,
06560          "Parking lot %s has parked calls.  Could not remove.\n",
06561          parkinglot->name);
06562       parkinglot->disabled = 1;
06563       force_reload_load = 1;
06564    }
06565 
06566    return 0;
06567 }
06568 
06569 static int parkinglot_activate_cb(void *obj, void *arg, int flags)
06570 {
06571    struct ast_parkinglot *parkinglot = obj;
06572 
06573    if (parkinglot->the_mark) {
06574       /*
06575        * Don't activate a parking lot that still bears the_mark since
06576        * it is effectively deleted.
06577        */
06578       return 0;
06579    }
06580 
06581    if (parkinglot_activate(parkinglot)) {
06582       /*
06583        * The parking lot failed to activate.  Allow reloading later to
06584        * see if that fixes it.
06585        */
06586       force_reload_load = 1;
06587       ast_log(LOG_WARNING, "Parking lot %s not open for business.\n", parkinglot->name);
06588    } else {
06589       ast_debug(1, "Parking lot %s now open for business. (parkpos %d-%d)\n",
06590          parkinglot->name, parkinglot->cfg.parking_start,
06591          parkinglot->cfg.parking_stop);
06592    }
06593 
06594    return 0;
06595 }
06596 
06597 static int load_config(int reload)
06598 {
06599    struct ast_flags config_flags = {
06600       reload && !force_reload_load ? CONFIG_FLAG_FILEUNCHANGED : 0 };
06601    struct ast_config *cfg;
06602    struct parking_dp_map old_usage_map = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
06603    struct parking_dp_map new_usage_map = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
06604 
06605    /* We are reloading now and have already determined if we will force the reload. */
06606    force_reload_load = 0;
06607 
06608    if (!default_parkinglot) {
06609       /* Must create the default default parking lot */
06610       default_parkinglot = build_parkinglot(DEFAULT_PARKINGLOT, NULL);
06611       if (!default_parkinglot) {
06612          ast_log(LOG_ERROR, "Configuration of default default parking lot failed.\n");
06613          return -1;
06614       }
06615       ast_debug(1, "Configuration of default default parking lot done.\n");
06616       parkinglot_addref(default_parkinglot);
06617    }
06618 
06619    cfg = ast_config_load2("features.conf", "features", config_flags);
06620    if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
06621       /* No sense in asking for reload trouble if nothing changed. */
06622       ast_debug(1, "features.conf did not change.\n");
06623       return 0;
06624    }
06625    if (cfg == CONFIG_STATUS_FILEMISSING
06626       || cfg == CONFIG_STATUS_FILEINVALID) {
06627       ast_log(LOG_WARNING, "Could not load features.conf\n");
06628       return 0;
06629    }
06630 
06631    /* Save current parking lot dialplan needs. */
06632    if (build_dialplan_useage_map(&old_usage_map, 0)) {
06633       destroy_dialplan_usage_map(&old_usage_map);
06634 
06635       /* Allow reloading later to see if conditions have improved. */
06636       force_reload_load = 1;
06637       return -1;
06638    }
06639 
06640    ao2_t_callback(parkinglots, OBJ_NODATA, parkinglot_markall_cb, NULL,
06641       "callback to mark all parking lots");
06642    process_config(cfg);
06643    ast_config_destroy(cfg);
06644    ao2_t_callback(parkinglots, OBJ_NODATA | OBJ_UNLINK, parkinglot_is_marked_cb, NULL,
06645       "callback to remove marked parking lots");
06646 
06647    /* Save updated parking lot dialplan needs. */
06648    if (build_dialplan_useage_map(&new_usage_map, 1)) {
06649       /*
06650        * Yuck, if this failure caused any parking lot dialplan items
06651        * to be lost, they will likely remain lost until Asterisk is
06652        * restarted.
06653        */
06654       destroy_dialplan_usage_map(&old_usage_map);
06655       destroy_dialplan_usage_map(&new_usage_map);
06656       return -1;
06657    }
06658 
06659    /* Remove no longer needed parking lot dialplan usage. */
06660    remove_dead_dialplan_useage(&old_usage_map, &new_usage_map);
06661 
06662    destroy_dialplan_usage_map(&old_usage_map);
06663    destroy_dialplan_usage_map(&new_usage_map);
06664 
06665    ao2_t_callback(parkinglots, OBJ_NODATA, parkinglot_activate_cb, NULL,
06666       "callback to activate all parking lots");
06667 
06668    return 0;
06669 }
06670 
06671 /*!
06672  * \brief CLI command to list configured features
06673  * \param e
06674  * \param cmd
06675  * \param a
06676  *
06677  * \retval CLI_SUCCESS on success.
06678  * \retval NULL when tab completion is used.
06679  */
06680 static char *handle_feature_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06681 {
06682    int i;
06683    struct ast_call_feature *feature;
06684    struct ao2_iterator iter;
06685    struct ast_parkinglot *curlot;
06686 #define HFS_FORMAT "%-25s %-7s %-7s\n"
06687 
06688    switch (cmd) {
06689    
06690    case CLI_INIT:
06691       e->command = "features show";
06692       e->usage =
06693          "Usage: features show\n"
06694          "       Lists configured features\n";
06695       return NULL;
06696    case CLI_GENERATE:
06697       return NULL;
06698    }
06699 
06700    ast_cli(a->fd, HFS_FORMAT, "Builtin Feature", "Default", "Current");
06701    ast_cli(a->fd, HFS_FORMAT, "---------------", "-------", "-------");
06702 
06703    ast_cli(a->fd, HFS_FORMAT, "Pickup", "*8", ast_pickup_ext());          /* default hardcoded above, so we'll hardcode it here */
06704 
06705    ast_rwlock_rdlock(&features_lock);
06706    for (i = 0; i < FEATURES_COUNT; i++)
06707       ast_cli(a->fd, HFS_FORMAT, builtin_features[i].fname, builtin_features[i].default_exten, builtin_features[i].exten);
06708    ast_rwlock_unlock(&features_lock);
06709 
06710    ast_cli(a->fd, "\n");
06711    ast_cli(a->fd, HFS_FORMAT, "Dynamic Feature", "Default", "Current");
06712    ast_cli(a->fd, HFS_FORMAT, "---------------", "-------", "-------");
06713    if (AST_RWLIST_EMPTY(&feature_list)) {
06714       ast_cli(a->fd, "(none)\n");
06715    } else {
06716       AST_RWLIST_RDLOCK(&feature_list);
06717       AST_RWLIST_TRAVERSE(&feature_list, feature, feature_entry) {
06718          ast_cli(a->fd, HFS_FORMAT, feature->sname, "no def", feature->exten);
06719       }
06720       AST_RWLIST_UNLOCK(&feature_list);
06721    }
06722 
06723    ast_cli(a->fd, "\nFeature Groups:\n");
06724    ast_cli(a->fd, "---------------\n");
06725    if (AST_RWLIST_EMPTY(&feature_groups)) {
06726       ast_cli(a->fd, "(none)\n");
06727    } else {
06728       struct feature_group *fg;
06729       struct feature_group_exten *fge;
06730 
06731       AST_RWLIST_RDLOCK(&feature_groups);
06732       AST_RWLIST_TRAVERSE(&feature_groups, fg, entry) {
06733          ast_cli(a->fd, "===> Group: %s\n", fg->gname);
06734          AST_LIST_TRAVERSE(&fg->features, fge, entry) {
06735             ast_cli(a->fd, "===> --> %s (%s)\n", fge->feature->sname, fge->exten);
06736          }
06737       }
06738       AST_RWLIST_UNLOCK(&feature_groups);
06739    }
06740 
06741    iter = ao2_iterator_init(parkinglots, 0);
06742    while ((curlot = ao2_iterator_next(&iter))) {
06743       ast_cli(a->fd, "\nCall parking (Parking lot: %s)\n", curlot->name);
06744       ast_cli(a->fd, "------------\n");
06745       ast_cli(a->fd,"%-22s:      %s\n", "Parking extension", curlot->cfg.parkext);
06746       ast_cli(a->fd,"%-22s:      %s\n", "Parking context", curlot->cfg.parking_con);
06747       ast_cli(a->fd,"%-22s:      %d-%d\n", "Parked call extensions",
06748          curlot->cfg.parking_start, curlot->cfg.parking_stop);
06749       ast_cli(a->fd,"%-22s:      %d ms\n", "Parkingtime", curlot->cfg.parkingtime);
06750       ast_cli(a->fd,"%-22s:      %s\n", "MusicOnHold class", curlot->cfg.mohclass);
06751       ast_cli(a->fd,"%-22s:      %s\n", "Enabled", AST_CLI_YESNO(!curlot->disabled));
06752       ast_cli(a->fd,"\n");
06753       ao2_ref(curlot, -1);
06754    }
06755    ao2_iterator_destroy(&iter);
06756 
06757    return CLI_SUCCESS;
06758 }
06759 
06760 int ast_features_reload(void)
06761 {
06762    struct ast_context *con;
06763    int res;
06764 
06765    ast_mutex_lock(&features_reload_lock);/* Searialize reloading features.conf */
06766 
06767    /*
06768     * Always destroy the parking_con_dial context to remove buildup
06769     * of recalled extensions in the context.  At worst, the parked
06770     * call gets hungup attempting to run an invalid extension when
06771     * we are trying to callback the parker or the preset return
06772     * extension.  This is a small window of opportunity on an
06773     * execution chain that is not expected to happen very often.
06774     */
06775    con = ast_context_find(parking_con_dial);
06776    if (con) {
06777       ast_context_destroy(con, registrar);
06778    }
06779 
06780    res = load_config(1);
06781    ast_mutex_unlock(&features_reload_lock);
06782 
06783    return res;
06784 }
06785 
06786 static char *handle_features_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06787 {
06788    switch (cmd) { 
06789    case CLI_INIT:
06790       e->command = "features reload";
06791       e->usage =
06792          "Usage: features reload\n"
06793          "       Reloads configured call features from features.conf\n";
06794       return NULL;
06795    case CLI_GENERATE:
06796       return NULL;
06797    }
06798    ast_features_reload();
06799 
06800    return CLI_SUCCESS;
06801 }
06802 
06803 /*!
06804  * \brief Actual bridge
06805  * \param chan
06806  * \param tmpchan
06807  *
06808  * Stop hold music, lock both channels, masq channels,
06809  * after bridge return channel to next priority.
06810  *
06811  * \retval 0 on success.
06812  * \retval -1 on error.
06813  */
06814 static int do_bridge_masquerade(struct ast_channel *chan, struct ast_channel *tmpchan)
06815 {
06816    const char *context;
06817    const char *exten;
06818    int priority;
06819 
06820    ast_moh_stop(chan);
06821    ast_channel_lock_both(chan, tmpchan);
06822    context = ast_strdupa(chan->context);
06823    exten = ast_strdupa(chan->exten);
06824    priority = chan->priority;
06825    ast_setstate(tmpchan, chan->_state);
06826    tmpchan->readformat = chan->readformat;
06827    tmpchan->writeformat = chan->writeformat;
06828    ast_channel_unlock(chan);
06829    ast_channel_unlock(tmpchan);
06830 
06831    /* Masquerade setup and execution must be done without any channel locks held */
06832    if (ast_channel_masquerade(tmpchan, chan)) {
06833       return -1;
06834    }
06835    ast_do_masquerade(tmpchan);
06836 
06837    /* when returning from bridge, the channel will continue at the next priority */
06838    ast_explicit_goto(tmpchan, context, exten, priority + 1);
06839 
06840    return 0;
06841 }
06842 
06843 /*!
06844  * \brief Bridge channels together
06845  * \param s
06846  * \param m
06847  *
06848  * Make sure valid channels were specified,
06849  * send errors if any of the channels could not be found/locked, answer channels if needed,
06850  * create the placeholder channels and grab the other channels
06851  * make the channels compatible, send error if we fail doing so
06852  * setup the bridge thread object and start the bridge.
06853  *
06854  * \retval 0
06855  */
06856 static int action_bridge(struct mansession *s, const struct message *m)
06857 {
06858    const char *channela = astman_get_header(m, "Channel1");
06859    const char *channelb = astman_get_header(m, "Channel2");
06860    const char *playtone = astman_get_header(m, "Tone");
06861    struct ast_channel *chana = NULL, *chanb = NULL, *chans[2];
06862    struct ast_channel *tmpchana = NULL, *tmpchanb = NULL;
06863    struct ast_bridge_thread_obj *tobj = NULL;
06864    char buf[256];
06865 
06866    /* make sure valid channels were specified */
06867    if (ast_strlen_zero(channela) || ast_strlen_zero(channelb)) {
06868       astman_send_error(s, m, "Missing channel parameter in request");
06869       return 0;
06870    }
06871 
06872    /* Start with chana */
06873    chana = ast_channel_get_by_name_prefix(channela, strlen(channela));
06874    if (!chana) {
06875       snprintf(buf, sizeof(buf), "Channel1 does not exists: %s", channela);
06876       astman_send_error(s, m, buf);
06877       return 0;
06878    }
06879 
06880    /* Answer the channels if needed */
06881    if (chana->_state != AST_STATE_UP)
06882       ast_answer(chana);
06883 
06884    /* create the placeholder channels and grab the other channels */
06885    if (!(tmpchana = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL, 
06886       NULL, NULL, chana->linkedid, 0, "Bridge/%s", chana->name))) {
06887       astman_send_error(s, m, "Unable to create temporary channel!");
06888       chana = ast_channel_unref(chana);
06889       return 0;
06890    }
06891 
06892    if (do_bridge_masquerade(chana, tmpchana)) {
06893       snprintf(buf, sizeof(buf), "Unable to masquerade channel %s!", channela);
06894       astman_send_error(s, m, buf);
06895       ast_hangup(tmpchana);
06896       chana = ast_channel_unref(chana);
06897       return 0;
06898    }
06899 
06900    chana = ast_channel_unref(chana);
06901 
06902    /* now do chanb */
06903    chanb = ast_channel_get_by_name_prefix(channelb, strlen(channelb));
06904    if (!chanb) {
06905       snprintf(buf, sizeof(buf), "Channel2 does not exists: %s", channelb);
06906       astman_send_error(s, m, buf);
06907       ast_hangup(tmpchana);
06908       return 0;
06909    }
06910 
06911    /* Answer the channels if needed */
06912    if (chanb->_state != AST_STATE_UP)
06913       ast_answer(chanb);
06914 
06915    /* create the placeholder channels and grab the other channels */
06916    if (!(tmpchanb = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL, 
06917       NULL, NULL, chanb->linkedid, 0, "Bridge/%s", chanb->name))) {
06918       astman_send_error(s, m, "Unable to create temporary channels!");
06919       ast_hangup(tmpchana);
06920       chanb = ast_channel_unref(chanb);
06921       return 0;
06922    }
06923 
06924    if (do_bridge_masquerade(chanb, tmpchanb)) {
06925       snprintf(buf, sizeof(buf), "Unable to masquerade channel %s!", channelb);
06926       astman_send_error(s, m, buf);
06927       ast_hangup(tmpchana);
06928       ast_hangup(tmpchanb);
06929       chanb = ast_channel_unref(chanb);
06930       return 0;
06931    }
06932 
06933    chanb = ast_channel_unref(chanb);
06934 
06935    /* make the channels compatible, send error if we fail doing so */
06936    if (ast_channel_make_compatible(tmpchana, tmpchanb)) {
06937       ast_log(LOG_WARNING, "Could not make channels %s and %s compatible for manager bridge\n", tmpchana->name, tmpchanb->name);
06938       astman_send_error(s, m, "Could not make channels compatible for manager bridge");
06939       ast_hangup(tmpchana);
06940       ast_hangup(tmpchanb);
06941       return 0;
06942    }
06943 
06944    /* setup the bridge thread object and start the bridge */
06945    if (!(tobj = ast_calloc(1, sizeof(*tobj)))) {
06946       ast_log(LOG_WARNING, "Unable to spawn a new bridge thread on %s and %s: %s\n", tmpchana->name, tmpchanb->name, strerror(errno));
06947       astman_send_error(s, m, "Unable to spawn a new bridge thread");
06948       ast_hangup(tmpchana);
06949       ast_hangup(tmpchanb);
06950       return 0;
06951    }
06952 
06953    tobj->chan = tmpchana;
06954    tobj->peer = tmpchanb;
06955    tobj->return_to_pbx = 1;
06956 
06957    if (ast_true(playtone)) {
06958       if (!ast_strlen_zero(xfersound) && !ast_streamfile(tmpchanb, xfersound, tmpchanb->language)) {
06959          if (ast_waitstream(tmpchanb, "") < 0)
06960             ast_log(LOG_WARNING, "Failed to play a courtesy tone on chan %s\n", tmpchanb->name);
06961       }
06962    }
06963 
06964    chans[0] = tmpchana;
06965    chans[1] = tmpchanb;
06966 
06967    ast_manager_event_multichan(EVENT_FLAG_CALL, "BridgeAction", 2, chans,
06968             "Response: Success\r\n"
06969             "Channel1: %s\r\n"
06970             "Channel2: %s\r\n", tmpchana->name, tmpchanb->name);
06971 
06972    bridge_call_thread_launch(tobj);
06973 
06974    astman_send_ack(s, m, "Launched bridge thread with success");
06975 
06976    return 0;
06977 }
06978 
06979 /*!
06980  * \brief CLI command to list parked calls
06981  * \param e 
06982  * \param cmd
06983  * \param a
06984  *  
06985  * Check right usage, lock parking lot, display parked calls, unlock parking lot list.
06986  * \retval CLI_SUCCESS on success.
06987  * \retval CLI_SHOWUSAGE on incorrect number of arguments.
06988  * \retval NULL when tab completion is used.
06989  */
06990 static char *handle_parkedcalls(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06991 {
06992    struct parkeduser *cur;
06993    int numparked = 0;
06994    struct ao2_iterator iter;
06995    struct ast_parkinglot *curlot;
06996 
06997    switch (cmd) {
06998    case CLI_INIT:
06999       e->command = "parkedcalls show";
07000       e->usage =
07001          "Usage: parkedcalls show\n"
07002          "       List currently parked calls\n";
07003       return NULL;
07004    case CLI_GENERATE:
07005       return NULL;
07006    }
07007 
07008    if (a->argc > e->args)
07009       return CLI_SHOWUSAGE;
07010 
07011    ast_cli(a->fd, "%-10s %-25s (%-15s %-12s %4s) %s\n", "Num", "Channel",
07012       "Context", "Extension", "Pri", "Timeout");
07013 
07014    iter = ao2_iterator_init(parkinglots, 0);
07015    while ((curlot = ao2_iterator_next(&iter))) {
07016       int lotparked = 0;
07017 
07018       /* subtract ref for iterator and for configured parking lot */
07019       ast_cli(a->fd, "*** Parking lot: %s (%d)\n", curlot->name,
07020          ao2_ref(curlot, 0) - 2 - (curlot == default_parkinglot));
07021 
07022       AST_LIST_LOCK(&curlot->parkings);
07023       AST_LIST_TRAVERSE(&curlot->parkings, cur, list) {
07024          ast_cli(a->fd, "%-10.10s %-25s (%-15s %-12s %4d) %6lds\n",
07025             cur->parkingexten, cur->chan->name, cur->context, cur->exten,
07026             cur->priority,
07027             (long) (cur->start.tv_sec + (cur->parkingtime / 1000) - time(NULL)));
07028          ++lotparked;
07029       }
07030       AST_LIST_UNLOCK(&curlot->parkings);
07031       if (lotparked) {
07032          numparked += lotparked;
07033          ast_cli(a->fd, "   %d parked call%s in parking lot %s\n", lotparked,
07034             ESS(lotparked), curlot->name);
07035       }
07036 
07037       ao2_ref(curlot, -1);
07038    }
07039    ao2_iterator_destroy(&iter);
07040 
07041    ast_cli(a->fd, "---\n%d parked call%s in total.\n", numparked, ESS(numparked));
07042 
07043    return CLI_SUCCESS;
07044 }
07045 
07046 static struct ast_cli_entry cli_features[] = {
07047    AST_CLI_DEFINE(handle_feature_show, "Lists configured features"),
07048    AST_CLI_DEFINE(handle_features_reload, "Reloads configured features"),
07049    AST_CLI_DEFINE(handle_parkedcalls, "List currently parked calls"),
07050 };
07051 
07052 /*! 
07053  * \brief Dump parking lot status
07054  * \param s
07055  * \param m
07056  * 
07057  * Lock parking lot, iterate list and append parked calls status, unlock parking lot.
07058  * \return Always RESULT_SUCCESS 
07059  */
07060 static int manager_parking_status(struct mansession *s, const struct message *m)
07061 {
07062    struct parkeduser *cur;
07063    const char *id = astman_get_header(m, "ActionID");
07064    char idText[256] = "";
07065    struct ao2_iterator iter;
07066    struct ast_parkinglot *curlot;
07067    int numparked = 0;
07068 
07069    if (!ast_strlen_zero(id))
07070       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
07071 
07072    astman_send_ack(s, m, "Parked calls will follow");
07073 
07074    iter = ao2_iterator_init(parkinglots, 0);
07075    while ((curlot = ao2_iterator_next(&iter))) {
07076       AST_LIST_LOCK(&curlot->parkings);
07077       AST_LIST_TRAVERSE(&curlot->parkings, cur, list) {
07078          astman_append(s, "Event: ParkedCall\r\n"
07079             "Parkinglot: %s\r\n"
07080             "Exten: %d\r\n"
07081             "Channel: %s\r\n"
07082             "From: %s\r\n"
07083             "Timeout: %ld\r\n"
07084             "CallerIDNum: %s\r\n"
07085             "CallerIDName: %s\r\n"
07086             "ConnectedLineNum: %s\r\n"
07087             "ConnectedLineName: %s\r\n"
07088             "%s"
07089             "\r\n",
07090             curlot->name,
07091             cur->parkingnum, cur->chan->name, cur->peername,
07092             (long) cur->start.tv_sec + (long) (cur->parkingtime / 1000) - (long) time(NULL),
07093             S_COR(cur->chan->caller.id.number.valid, cur->chan->caller.id.number.str, ""),   /* XXX in other places it is <unknown> */
07094             S_COR(cur->chan->caller.id.name.valid, cur->chan->caller.id.name.str, ""),
07095             S_COR(cur->chan->connected.id.number.valid, cur->chan->connected.id.number.str, ""),   /* XXX in other places it is <unknown> */
07096             S_COR(cur->chan->connected.id.name.valid, cur->chan->connected.id.name.str, ""),
07097             idText);
07098          ++numparked;
07099       }
07100       AST_LIST_UNLOCK(&curlot->parkings);
07101       ao2_ref(curlot, -1);
07102    }
07103    ao2_iterator_destroy(&iter);
07104 
07105    astman_append(s,
07106       "Event: ParkedCallsComplete\r\n"
07107       "Total: %d\r\n"
07108       "%s"
07109       "\r\n",
07110       numparked, idText);
07111 
07112    return RESULT_SUCCESS;
07113 }
07114 
07115 /*!
07116  * \brief Create manager event for parked calls
07117  * \param s
07118  * \param m
07119  *
07120  * Get channels involved in park, create event.
07121  * \return Always 0
07122  *
07123  * \note ADSI is not compatible with this AMI action for the
07124  * same reason ch2 can no longer announce the parking space.
07125  */
07126 static int manager_park(struct mansession *s, const struct message *m)
07127 {
07128    const char *channel = astman_get_header(m, "Channel");
07129    const char *channel2 = astman_get_header(m, "Channel2");
07130    const char *timeout = astman_get_header(m, "Timeout");
07131    const char *parkinglotname = astman_get_header(m, "Parkinglot");
07132    char buf[BUFSIZ];
07133    int res = 0;
07134    struct ast_channel *ch1, *ch2;
07135    struct ast_park_call_args args = {
07136          /*
07137           * Don't say anything to ch2 since AMI is a third party parking
07138           * a call and we will likely crash if we do.
07139           *
07140           * XXX When the AMI action was originally implemented, the
07141           * parking space was announced to ch2.  Unfortunately, grabbing
07142           * the ch2 lock and holding it while the announcement is played
07143           * was not really a good thing to do to begin with since it
07144           * could hold up the system.  Also holding the lock is no longer
07145           * possible with a masquerade.
07146           *
07147           * Restoring the announcement to ch2 is not easily doable for
07148           * the following reasons:
07149           *
07150           * 1) The AMI manager is not the thread processing ch2.
07151           *
07152           * 2) ch2 could be the same as ch1, bridged to ch1, or some
07153           * random uninvolved channel.
07154           */
07155          .flags = AST_PARK_OPT_SILENCE,
07156       };
07157 
07158    if (ast_strlen_zero(channel)) {
07159       astman_send_error(s, m, "Channel not specified");
07160       return 0;
07161    }
07162 
07163    if (ast_strlen_zero(channel2)) {
07164       astman_send_error(s, m, "Channel2 not specified");
07165       return 0;
07166    }
07167 
07168    if (!ast_strlen_zero(timeout)) {
07169       if (sscanf(timeout, "%30d", &args.timeout) != 1) {
07170          astman_send_error(s, m, "Invalid timeout value.");
07171          return 0;
07172       }
07173    }
07174 
07175    if (!(ch1 = ast_channel_get_by_name(channel))) {
07176       snprintf(buf, sizeof(buf), "Channel does not exist: %s", channel);
07177       astman_send_error(s, m, buf);
07178       return 0;
07179    }
07180 
07181    if (!(ch2 = ast_channel_get_by_name(channel2))) {
07182       snprintf(buf, sizeof(buf), "Channel does not exist: %s", channel2);
07183       astman_send_error(s, m, buf);
07184       ast_channel_unref(ch1);
07185       return 0;
07186    }
07187 
07188    if (!ast_strlen_zero(parkinglotname)) {
07189       args.parkinglot = find_parkinglot(parkinglotname);
07190    }
07191 
07192    res = masq_park_call(ch1, ch2, &args);
07193    if (!res) {
07194       ast_softhangup(ch2, AST_SOFTHANGUP_EXPLICIT);
07195       astman_send_ack(s, m, "Park successful");
07196    } else {
07197       astman_send_error(s, m, "Park failure");
07198    }
07199 
07200    if (args.parkinglot) {
07201       parkinglot_unref(args.parkinglot);
07202    }
07203    ch1 = ast_channel_unref(ch1);
07204    ch2 = ast_channel_unref(ch2);
07205 
07206    return 0;
07207 }
07208 
07209 /*!
07210  * The presence of this datastore on the channel indicates that
07211  * someone is attemting to pickup or has picked up the channel.
07212  * The purpose is to prevent a race between two channels
07213  * attempting to pickup the same channel.
07214  */
07215 static const struct ast_datastore_info pickup_active = {
07216    .type = "pickup-active",
07217 };
07218 
07219 int ast_can_pickup(struct ast_channel *chan)
07220 {
07221    if (!chan->pbx && !chan->masq && !ast_test_flag(chan, AST_FLAG_ZOMBIE)
07222       && (chan->_state == AST_STATE_RINGING
07223          || chan->_state == AST_STATE_RING
07224          /*
07225           * Check the down state as well because some SIP devices do not
07226           * give 180 ringing when they can just give 183 session progress
07227           * instead.  Issue 14005.  (Some ISDN switches as well for that
07228           * matter.)
07229           */
07230          || chan->_state == AST_STATE_DOWN)
07231       && !ast_channel_datastore_find(chan, &pickup_active, NULL)) {
07232       return 1;
07233    }
07234    return 0;
07235 }
07236 
07237 static int find_channel_by_group(void *obj, void *arg, void *data, int flags)
07238 {
07239    struct ast_channel *target = obj;/*!< Potential pickup target */
07240    struct ast_channel *chan = data;/*!< Channel wanting to pickup call */
07241 
07242    ast_channel_lock(target);
07243    if (chan != target && (chan->pickupgroup & target->callgroup)
07244       && ast_can_pickup(target)) {
07245       /* Return with the channel still locked on purpose */
07246       return CMP_MATCH | CMP_STOP;
07247    }
07248    ast_channel_unlock(target);
07249 
07250    return 0;
07251 }
07252 
07253 /*!
07254  * \brief Pickup a call
07255  * \param chan channel that initiated pickup.
07256  *
07257  * Walk list of channels, checking it is not itself, channel is pbx one,
07258  * check that the callgroup for both channels are the same and the channel is ringing.
07259  * Answer calling channel, flag channel as answered on queue, masq channels together.
07260  */
07261 int ast_pickup_call(struct ast_channel *chan)
07262 {
07263    struct ast_channel *target;/*!< Potential pickup target */
07264    int res = -1;
07265    ast_debug(1, "pickup attempt by %s\n", chan->name);
07266 
07267    /* The found channel is already locked. */
07268    target = ast_channel_callback(find_channel_by_group, NULL, chan, 0);
07269    if (target) {
07270       ast_log(LOG_NOTICE, "pickup %s attempt by %s\n", target->name, chan->name);
07271 
07272       res = ast_do_pickup(chan, target);
07273       ast_channel_unlock(target);
07274       if (!res) {
07275          if (!ast_strlen_zero(pickupsound)) {
07276             pbx_builtin_setvar_helper(target, "BRIDGE_PLAY_SOUND", pickupsound);
07277          }
07278       } else {
07279          ast_log(LOG_WARNING, "pickup %s failed by %s\n", target->name, chan->name);
07280       }
07281       target = ast_channel_unref(target);
07282    }
07283 
07284    if (res < 0) {
07285       ast_debug(1, "No call pickup possible... for %s\n", chan->name);
07286       if (!ast_strlen_zero(pickupfailsound)) {
07287          ast_answer(chan);
07288          ast_stream_and_wait(chan, pickupfailsound, "");
07289       }
07290    }
07291 
07292    return res;
07293 }
07294 
07295 int ast_do_pickup(struct ast_channel *chan, struct ast_channel *target)
07296 {
07297    struct ast_party_connected_line connected_caller;
07298    struct ast_channel *chans[2] = { chan, target };
07299    struct ast_datastore *ds_pickup;
07300    const char *chan_name;/*!< A masquerade changes channel names. */
07301    const char *target_name;/*!< A masquerade changes channel names. */
07302    int res = -1;
07303 
07304    target_name = ast_strdupa(target->name);
07305    ast_debug(1, "Call pickup on '%s' by '%s'\n", target_name, chan->name);
07306 
07307    /* Mark the target to block any call pickup race. */
07308    ds_pickup = ast_datastore_alloc(&pickup_active, NULL);
07309    if (!ds_pickup) {
07310       ast_log(LOG_WARNING,
07311          "Unable to create channel datastore on '%s' for call pickup\n", target_name);
07312       return -1;
07313    }
07314    ast_channel_datastore_add(target, ds_pickup);
07315 
07316    ast_party_connected_line_init(&connected_caller);
07317    ast_party_connected_line_copy(&connected_caller, &target->connected);
07318    ast_channel_unlock(target);/* The pickup race is avoided so we do not need the lock anymore. */
07319    connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
07320    if (ast_channel_connected_line_macro(NULL, chan, &connected_caller, 0, 0)) {
07321       ast_channel_update_connected_line(chan, &connected_caller, NULL);
07322    }
07323    ast_party_connected_line_free(&connected_caller);
07324 
07325    ast_channel_lock(chan);
07326    chan_name = ast_strdupa(chan->name);
07327    ast_connected_line_copy_from_caller(&connected_caller, &chan->caller);
07328    ast_channel_unlock(chan);
07329    connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
07330 
07331    ast_cel_report_event(target, AST_CEL_PICKUP, NULL, NULL, chan);
07332 
07333    if (ast_answer(chan)) {
07334       ast_log(LOG_WARNING, "Unable to answer '%s'\n", chan_name);
07335       goto pickup_failed;
07336    }
07337 
07338    if (ast_queue_control(chan, AST_CONTROL_ANSWER)) {
07339       ast_log(LOG_WARNING, "Unable to queue answer on '%s'\n", chan_name);
07340       goto pickup_failed;
07341    }
07342    
07343    ast_channel_queue_connected_line_update(chan, &connected_caller, NULL);
07344 
07345    /* setting this flag to generate a reason header in the cancel message to the ringing channel */
07346    ast_set_flag(chan, AST_FLAG_ANSWERED_ELSEWHERE);
07347 
07348    if (ast_channel_masquerade(target, chan)) {
07349       ast_log(LOG_WARNING, "Unable to masquerade '%s' into '%s'\n", chan_name,
07350          target_name);
07351       goto pickup_failed;
07352    }
07353 
07354    /* If you want UniqueIDs, set channelvars in manager.conf to CHANNEL(uniqueid) */
07355    ast_manager_event_multichan(EVENT_FLAG_CALL, "Pickup", 2, chans,
07356       "Channel: %s\r\n"
07357       "TargetChannel: %s\r\n",
07358       chan_name, target_name);
07359 
07360    /* Do the masquerade manually to make sure that it is completed. */
07361    ast_do_masquerade(target);
07362    res = 0;
07363 
07364 pickup_failed:
07365    ast_channel_lock(target);
07366    if (!ast_channel_datastore_remove(target, ds_pickup)) {
07367       ast_datastore_free(ds_pickup);
07368    }
07369    ast_party_connected_line_free(&connected_caller);
07370 
07371    return res;
07372 }
07373 
07374 static char *app_bridge = "Bridge";
07375 
07376 enum {
07377    BRIDGE_OPT_PLAYTONE = (1 << 0),
07378    OPT_CALLEE_HANGUP =  (1 << 1),
07379    OPT_CALLER_HANGUP =  (1 << 2),
07380    OPT_DURATION_LIMIT = (1 << 3),
07381    OPT_DURATION_STOP =  (1 << 4),
07382    OPT_CALLEE_TRANSFER = (1 << 5),
07383    OPT_CALLER_TRANSFER = (1 << 6),
07384    OPT_CALLEE_MONITOR = (1 << 7),
07385    OPT_CALLER_MONITOR = (1 << 8),
07386    OPT_CALLEE_PARK = (1 << 9),
07387    OPT_CALLER_PARK = (1 << 10),
07388    OPT_CALLEE_KILL = (1 << 11),
07389 };
07390  
07391 enum {
07392    OPT_ARG_DURATION_LIMIT = 0,
07393    OPT_ARG_DURATION_STOP,
07394    /* note: this entry _MUST_ be the last one in the enum */
07395    OPT_ARG_ARRAY_SIZE,
07396 };
07397 
07398 AST_APP_OPTIONS(bridge_exec_options, BEGIN_OPTIONS
07399    AST_APP_OPTION('p', BRIDGE_OPT_PLAYTONE),
07400    AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
07401    AST_APP_OPTION('H', OPT_CALLER_HANGUP),
07402    AST_APP_OPTION('k', OPT_CALLEE_PARK),
07403    AST_APP_OPTION('K', OPT_CALLER_PARK),
07404    AST_APP_OPTION_ARG('L', OPT_DURATION_LIMIT, OPT_ARG_DURATION_LIMIT),
07405    AST_APP_OPTION_ARG('S', OPT_DURATION_STOP, OPT_ARG_DURATION_STOP),
07406    AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
07407    AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
07408    AST_APP_OPTION('w', OPT_CALLEE_MONITOR),
07409    AST_APP_OPTION('W', OPT_CALLER_MONITOR),
07410    AST_APP_OPTION('x', OPT_CALLEE_KILL),
07411 END_OPTIONS );
07412 
07413 int ast_bridge_timelimit(struct ast_channel *chan, struct ast_bridge_config *config,
07414    char *parse, struct timeval *calldurationlimit)
07415 {
07416    char *stringp = ast_strdupa(parse);
07417    char *limit_str, *warning_str, *warnfreq_str;
07418    const char *var;
07419    int play_to_caller = 0, play_to_callee = 0;
07420    int delta;
07421 
07422    limit_str = strsep(&stringp, ":");
07423    warning_str = strsep(&stringp, ":");
07424    warnfreq_str = strsep(&stringp, ":");
07425 
07426    config->timelimit = atol(limit_str);
07427    if (warning_str)
07428       config->play_warning = atol(warning_str);
07429    if (warnfreq_str)
07430       config->warning_freq = atol(warnfreq_str);
07431 
07432    if (!config->timelimit) {
07433       ast_log(LOG_WARNING, "Bridge does not accept L(%s), hanging up.\n", limit_str);
07434       config->timelimit = config->play_warning = config->warning_freq = 0;
07435       config->warning_sound = NULL;
07436       return -1; /* error */
07437    } else if ( (delta = config->play_warning - config->timelimit) > 0) {
07438       int w = config->warning_freq;
07439 
07440       /*
07441        * If the first warning is requested _after_ the entire call
07442        * would end, and no warning frequency is requested, then turn
07443        * off the warning. If a warning frequency is requested, reduce
07444        * the 'first warning' time by that frequency until it falls
07445        * within the call's total time limit.
07446        *
07447        * Graphically:
07448        *                timelim->|    delta        |<-playwarning
07449        *      0__________________|_________________|
07450        *                       | w  |    |    |    |
07451        *
07452        * so the number of intervals to cut is 1+(delta-1)/w
07453        */
07454       if (w == 0) {
07455          config->play_warning = 0;
07456       } else {
07457          config->play_warning -= w * ( 1 + (delta-1)/w );
07458          if (config->play_warning < 1)
07459             config->play_warning = config->warning_freq = 0;
07460       }
07461    }
07462    
07463    ast_channel_lock(chan);
07464 
07465    var = pbx_builtin_getvar_helper(chan, "LIMIT_PLAYAUDIO_CALLER");
07466    play_to_caller = var ? ast_true(var) : 1;
07467 
07468    var = pbx_builtin_getvar_helper(chan, "LIMIT_PLAYAUDIO_CALLEE");
07469    play_to_callee = var ? ast_true(var) : 0;
07470 
07471    if (!play_to_caller && !play_to_callee)
07472       play_to_caller = 1;
07473 
07474    var = pbx_builtin_getvar_helper(chan, "LIMIT_WARNING_FILE");
07475    config->warning_sound = !ast_strlen_zero(var) ? ast_strdup(var) : ast_strdup("timeleft");
07476 
07477    /* The code looking at config wants a NULL, not just "", to decide
07478     * that the message should not be played, so we replace "" with NULL.
07479     * Note, pbx_builtin_getvar_helper _can_ return NULL if the variable is
07480     * not found.
07481     */
07482 
07483    var = pbx_builtin_getvar_helper(chan, "LIMIT_TIMEOUT_FILE");
07484    config->end_sound = !ast_strlen_zero(var) ? ast_strdup(var) : NULL;
07485 
07486    var = pbx_builtin_getvar_helper(chan, "LIMIT_CONNECT_FILE");
07487    config->start_sound = !ast_strlen_zero(var) ? ast_strdup(var) : NULL;
07488 
07489    ast_channel_unlock(chan);
07490 
07491    /* undo effect of S(x) in case they are both used */
07492    calldurationlimit->tv_sec = 0;
07493    calldurationlimit->tv_usec = 0;
07494 
07495    /* more efficient to do it like S(x) does since no advanced opts */
07496    if (!config->play_warning && !config->start_sound && !config->end_sound && config->timelimit) {
07497       calldurationlimit->tv_sec = config->timelimit / 1000;
07498       calldurationlimit->tv_usec = (config->timelimit % 1000) * 1000;
07499       ast_verb(3, "Setting call duration limit to %.3lf seconds.\n",
07500          calldurationlimit->tv_sec + calldurationlimit->tv_usec / 1000000.0);
07501       config->timelimit = play_to_caller = play_to_callee =
07502       config->play_warning = config->warning_freq = 0;
07503    } else {
07504       ast_verb(4, "Limit Data for this call:\n");
07505       ast_verb(4, "timelimit      = %ld ms (%.3lf s)\n", config->timelimit, config->timelimit / 1000.0);
07506       ast_verb(4, "play_warning   = %ld ms (%.3lf s)\n", config->play_warning, config->play_warning / 1000.0);
07507       ast_verb(4, "play_to_caller = %s\n", play_to_caller ? "yes" : "no");
07508       ast_verb(4, "play_to_callee = %s\n", play_to_callee ? "yes" : "no");
07509       ast_verb(4, "warning_freq   = %ld ms (%.3lf s)\n", config->warning_freq, config->warning_freq / 1000.0);
07510       ast_verb(4, "start_sound    = %s\n", S_OR(config->start_sound, ""));
07511       ast_verb(4, "warning_sound  = %s\n", config->warning_sound);
07512       ast_verb(4, "end_sound      = %s\n", S_OR(config->end_sound, ""));
07513    }
07514    if (play_to_caller)
07515       ast_set_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING);
07516    if (play_to_callee)
07517       ast_set_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING);
07518    return 0;
07519 }
07520 
07521 
07522 /*!
07523  * \brief Bridge channels
07524  * \param chan
07525  * \param data channel to bridge with.
07526  *
07527  * Split data, check we aren't bridging with ourself, check valid channel,
07528  * answer call if not already, check compatible channels, setup bridge config
07529  * now bridge call, if transfered party hangs up return to PBX extension.
07530  */
07531 static int bridge_exec(struct ast_channel *chan, const char *data)
07532 {
07533    struct ast_channel *current_dest_chan, *final_dest_chan, *chans[2];
07534    char *tmp_data  = NULL;
07535    struct ast_flags opts = { 0, };
07536    struct ast_bridge_config bconfig = { { 0, }, };
07537    char *opt_args[OPT_ARG_ARRAY_SIZE];
07538    struct timeval calldurationlimit = { 0, };
07539 
07540    AST_DECLARE_APP_ARGS(args,
07541       AST_APP_ARG(dest_chan);
07542       AST_APP_ARG(options);
07543    );
07544 
07545    if (ast_strlen_zero(data)) {
07546       ast_log(LOG_WARNING, "Bridge require at least 1 argument specifying the other end of the bridge\n");
07547       return -1;
07548    }
07549 
07550    tmp_data = ast_strdupa(data);
07551    AST_STANDARD_APP_ARGS(args, tmp_data);
07552    if (!ast_strlen_zero(args.options))
07553       ast_app_parse_options(bridge_exec_options, &opts, opt_args, args.options);
07554 
07555    /* avoid bridge with ourselves */
07556    if (!strcmp(chan->name, args.dest_chan)) {
07557       ast_log(LOG_WARNING, "Unable to bridge channel %s with itself\n", chan->name);
07558       ast_manager_event(chan, EVENT_FLAG_CALL, "BridgeExec",
07559          "Response: Failed\r\n"
07560          "Reason: Unable to bridge channel to itself\r\n"
07561          "Channel1: %s\r\n"
07562          "Channel2: %s\r\n",
07563          chan->name, args.dest_chan);
07564       pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "LOOP");
07565       return 0;
07566    }
07567 
07568    /* make sure we have a valid end point */
07569    if (!(current_dest_chan = ast_channel_get_by_name_prefix(args.dest_chan,
07570          strlen(args.dest_chan)))) {
07571       ast_log(LOG_WARNING, "Bridge failed because channel %s does not exist\n",
07572          args.dest_chan);
07573       ast_manager_event(chan, EVENT_FLAG_CALL, "BridgeExec",
07574          "Response: Failed\r\n"
07575          "Reason: Channel2 does not exist\r\n"
07576          "Channel1: %s\r\n"
07577          "Channel2: %s\r\n", chan->name, args.dest_chan);
07578       pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "NONEXISTENT");
07579       return 0;
07580    }
07581 
07582    /* try to allocate a place holder where current_dest_chan will be placed */
07583    if (!(final_dest_chan = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL, 
07584       NULL, NULL, current_dest_chan->linkedid, 0, "Bridge/%s", current_dest_chan->name))) {
07585       ast_log(LOG_WARNING, "Cannot create placeholder channel for chan %s\n", args.dest_chan);
07586       ast_manager_event(chan, EVENT_FLAG_CALL, "BridgeExec",
07587          "Response: Failed\r\n"
07588          "Reason: Cannot create placeholder channel\r\n"
07589          "Channel1: %s\r\n"
07590          "Channel2: %s\r\n", chan->name, args.dest_chan);
07591       pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "FAILURE");
07592       ast_channel_unref(current_dest_chan);
07593       return 0;
07594    }
07595 
07596    if (ast_test_flag(&opts, OPT_DURATION_LIMIT)
07597       && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_LIMIT])
07598       && ast_bridge_timelimit(chan, &bconfig, opt_args[OPT_ARG_DURATION_LIMIT], &calldurationlimit)) {
07599       ast_manager_event(chan, EVENT_FLAG_CALL, "BridgeExec",
07600          "Response: Failed\r\n"
07601          "Reason: Cannot setup bridge time limit\r\n"
07602          "Channel1: %s\r\n"
07603          "Channel2: %s\r\n", chan->name, args.dest_chan);
07604       ast_hangup(final_dest_chan);
07605       pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "FAILURE");
07606       current_dest_chan = ast_channel_unref(current_dest_chan);
07607       goto done;
07608    }
07609 
07610    if (do_bridge_masquerade(current_dest_chan, final_dest_chan)) {
07611       ast_manager_event(chan, EVENT_FLAG_CALL, "BridgeExec",
07612          "Response: Failed\r\n"
07613          "Reason: Cannot masquerade channels\r\n"
07614          "Channel1: %s\r\n"
07615          "Channel2: %s\r\n", chan->name, args.dest_chan);
07616       ast_hangup(final_dest_chan);
07617       pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "FAILURE");
07618       current_dest_chan = ast_channel_unref(current_dest_chan);
07619       goto done;
07620    }
07621 
07622    /* answer the channel if needed */
07623    if (final_dest_chan->_state != AST_STATE_UP) {
07624       ast_answer(final_dest_chan);
07625    }
07626 
07627    chans[0] = current_dest_chan;
07628    chans[1] = final_dest_chan;
07629 
07630    /* now current_dest_chan is a ZOMBIE and with softhangup set to 1 and final_dest_chan is our end point */
07631    /* try to make compatible, send error if we fail */
07632    if (ast_channel_make_compatible(chan, final_dest_chan) < 0) {
07633       ast_log(LOG_WARNING, "Could not make channels %s and %s compatible for bridge\n", chan->name, final_dest_chan->name);
07634       ast_manager_event_multichan(EVENT_FLAG_CALL, "BridgeExec", 2, chans,
07635          "Response: Failed\r\n"
07636          "Reason: Could not make channels compatible for bridge\r\n"
07637          "Channel1: %s\r\n"
07638          "Channel2: %s\r\n", chan->name, final_dest_chan->name);
07639 
07640       /* Maybe we should return this channel to the PBX? */
07641       ast_hangup(final_dest_chan);
07642 
07643       pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "INCOMPATIBLE");
07644       current_dest_chan = ast_channel_unref(current_dest_chan);
07645       goto done;
07646    }
07647 
07648    /* Report that the bridge will be successfull */
07649    ast_manager_event_multichan(EVENT_FLAG_CALL, "BridgeExec", 2, chans,
07650       "Response: Success\r\n"
07651       "Channel1: %s\r\n"
07652       "Channel2: %s\r\n", chan->name, final_dest_chan->name);
07653 
07654    current_dest_chan = ast_channel_unref(current_dest_chan);
07655 
07656    /* we have 2 valid channels to bridge, now it is just a matter of setting up the bridge config and starting the bridge */  
07657    if (ast_test_flag(&opts, BRIDGE_OPT_PLAYTONE) && !ast_strlen_zero(xfersound)) {
07658       if (!ast_streamfile(final_dest_chan, xfersound, final_dest_chan->language)) {
07659          if (ast_waitstream(final_dest_chan, "") < 0)
07660             ast_log(LOG_WARNING, "Failed to play courtesy tone on %s\n", final_dest_chan->name);
07661       }
07662    }
07663 
07664    if (ast_test_flag(&opts, OPT_CALLEE_TRANSFER))
07665       ast_set_flag(&(bconfig.features_callee), AST_FEATURE_REDIRECT);
07666    if (ast_test_flag(&opts, OPT_CALLER_TRANSFER))
07667       ast_set_flag(&(bconfig.features_caller), AST_FEATURE_REDIRECT);
07668    if (ast_test_flag(&opts, OPT_CALLEE_HANGUP))
07669       ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
07670    if (ast_test_flag(&opts, OPT_CALLER_HANGUP))
07671       ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
07672    if (ast_test_flag(&opts, OPT_CALLEE_MONITOR))
07673       ast_set_flag(&(bconfig.features_callee), AST_FEATURE_AUTOMON);
07674    if (ast_test_flag(&opts, OPT_CALLER_MONITOR))
07675       ast_set_flag(&(bconfig.features_caller), AST_FEATURE_AUTOMON);
07676    if (ast_test_flag(&opts, OPT_CALLEE_PARK))
07677       ast_set_flag(&(bconfig.features_callee), AST_FEATURE_PARKCALL);
07678    if (ast_test_flag(&opts, OPT_CALLER_PARK))
07679       ast_set_flag(&(bconfig.features_caller), AST_FEATURE_PARKCALL);
07680 
07681    /*
07682     * Don't let the after-bridge code run the h-exten.  We want to
07683     * continue in the dialplan.
07684     */
07685    ast_set_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT);
07686    ast_bridge_call(chan, final_dest_chan, &bconfig);
07687 
07688    /* The bridge has ended, set BRIDGERESULT to SUCCESS. */
07689    pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "SUCCESS");
07690 
07691    /* If the other channel has not been hung up, return it to the PBX */
07692    if (!ast_check_hangup(final_dest_chan)) {
07693       if (!ast_test_flag(&opts, OPT_CALLEE_KILL)) {
07694          ast_debug(1, "starting new PBX in %s,%s,%d for chan %s\n",
07695             final_dest_chan->context, final_dest_chan->exten,
07696             final_dest_chan->priority, final_dest_chan->name);
07697 
07698          if (ast_pbx_start(final_dest_chan)) {
07699             ast_log(LOG_WARNING, "FAILED continuing PBX on dest chan %s\n", final_dest_chan->name);
07700             ast_hangup(final_dest_chan);
07701          } else {
07702             ast_debug(1, "SUCCESS continuing PBX on chan %s\n", final_dest_chan->name);
07703          }
07704       } else {
07705          ast_hangup(final_dest_chan);
07706       }
07707    } else {
07708       ast_debug(1, "chan %s was hungup\n", final_dest_chan->name);
07709       ast_hangup(final_dest_chan);
07710    }
07711 done:
07712    ast_free((char *) bconfig.warning_sound);
07713    ast_free((char *) bconfig.end_sound);
07714    ast_free((char *) bconfig.start_sound);
07715 
07716    return 0;
07717 }
07718 
07719 #if defined(TEST_FRAMEWORK)
07720 /*!
07721  * \internal
07722  * \brief Convert parking spaces map list to a comma separated string.
07723  *
07724  * \param str String buffer to fill.
07725  * \param spaces Parking spaces map list to convert.
07726  *
07727  * \return Nothing
07728  */
07729 static void create_spaces_str(struct ast_str **str, struct parking_dp_space_map *spaces)
07730 {
07731    const char *comma;
07732    struct parking_dp_spaces *cur;
07733 
07734    ast_str_reset(*str);
07735    comma = "";
07736    AST_LIST_TRAVERSE(spaces, cur, node) {
07737       if (cur->start == cur->stop) {
07738          ast_str_append(str, 0, "%s%d", comma, cur->start);
07739       } else {
07740          ast_str_append(str, 0, "%s%d-%d", comma, cur->start, cur->stop);
07741       }
07742       comma = ",";
07743    }
07744 }
07745 #endif   /* defined(TEST_FRAMEWORK) */
07746 
07747 #if defined(TEST_FRAMEWORK)
07748 /*!
07749  * \internal
07750  * \brief Compare parking spaces map to what is expected.
07751  *
07752  * \param test Unit test context.
07753  * \param spaces Parking spaces map list to check.
07754  * \param expected String to compare with.
07755  * \param what What is being compared.
07756  *
07757  * \retval 0 successful compare.
07758  * \retval nonzero if failed to compare.
07759  */
07760 static int check_spaces(struct ast_test *test, struct parking_dp_space_map *spaces, const char *expected, const char *what)
07761 {
07762    int cmp;
07763    struct ast_str *str = ast_str_alloca(1024);
07764 
07765    create_spaces_str(&str, spaces);
07766    cmp = strcmp(expected, ast_str_buffer(str));
07767    if (cmp) {
07768       ast_test_status_update(test,
07769          "Unexpected parking space map for %s. Expect:'%s' Got:'%s'\n",
07770          what, expected, ast_str_buffer(str));
07771    }
07772    return cmp;
07773 }
07774 #endif   /* defined(TEST_FRAMEWORK) */
07775 
07776 #if defined(TEST_FRAMEWORK)
07777 /*!
07778  * \internal
07779  * \brief Add a dead space to the dead spaces list.
07780  *
07781  * \param context Dead spaces list ptr pretending to be a context name ptr.
07782  * \param space Dead space to add to the list.
07783  *
07784  * \return Nothing
07785  */
07786 static void test_add_dead_space(const char *context, int space)
07787 {
07788    struct parking_dp_space_map *dead_spaces = (struct parking_dp_space_map *) context;
07789 
07790    usage_context_add_spaces(dead_spaces, space, space, NULL, 0);
07791 }
07792 #endif   /* defined(TEST_FRAMEWORK) */
07793 
07794 #if defined(TEST_FRAMEWORK)
07795 struct test_map {
07796    const char *ramp;
07797    int start;
07798    int stop;
07799    const char *expect;
07800 };
07801 
07802 /*!
07803  * \internal
07804  * \brief Build a parking lot dialplan usage test map from a table.
07805  *
07806  * \param test Unit test context.
07807  * \param lot Parking lot to use to build test usage map.
07808  * \param table_name Name of passed in table.
07809  * \param table Usage information to put in the usage map.
07810  * \param num_entries Number of entries in the table.
07811  *
07812  * \retval Created context node on success.
07813  * \retval NULL on error.
07814  */
07815 static struct parking_dp_context *test_build_maps(struct ast_test *test,
07816    struct ast_parkinglot *lot, const char *table_name, const struct test_map *table,
07817    size_t num_entries)
07818 {
07819    struct parking_dp_context *ctx_node;
07820    int cur_index = 0;
07821    char what[40];
07822 
07823    snprintf(what, sizeof(what), "%s[%d]", table_name, cur_index);
07824    ast_copy_string(lot->cfg.parkext, table->ramp, sizeof(lot->cfg.parkext));
07825    lot->cfg.parking_start = table->start;
07826    lot->cfg.parking_stop = table->stop;
07827    ctx_node = build_dialplan_useage_context(lot);
07828    if (!ctx_node) {
07829       ast_test_status_update(test, "Failed to create parking lot context map for %s\n",
07830          what);
07831       return NULL;
07832    }
07833    if (check_spaces(test, &ctx_node->spaces, table->expect, what)) {
07834       destroy_dialplan_usage_context(ctx_node);
07835       return NULL;
07836    }
07837    while (--num_entries) {
07838       ++cur_index;
07839       ++table;
07840       snprintf(what, sizeof(what), "%s[%d]", table_name, cur_index);
07841       ast_copy_string(lot->cfg.parkext, table->ramp, sizeof(lot->cfg.parkext));
07842       lot->cfg.parking_start = table->start;
07843       lot->cfg.parking_stop = table->stop;
07844       if (dialplan_usage_add_parkinglot_data(ctx_node, lot, 1)) {
07845          ast_test_status_update(test, "Failed to add parking lot data for %s\n", what);
07846          destroy_dialplan_usage_context(ctx_node);
07847          return NULL;
07848       }
07849       if (check_spaces(test, &ctx_node->spaces, table->expect, what)) {
07850          destroy_dialplan_usage_context(ctx_node);
07851          return NULL;
07852       }
07853    }
07854    return ctx_node;
07855 }
07856 
07857 static const struct test_map test_old_ctx[] = {
07858    /* The following order of building ctx is important to test adding items to the lists. */
07859    { "702", 14, 15, "14-15" },
07860    { "700", 10, 11, "10-11,14-15" },
07861    { "701", 18, 19, "10-11,14-15,18-19" },
07862    { "703", 12, 13, "10-15,18-19" },
07863    { "704", 16, 17, "10-19" },
07864 
07865    /* Parking ramp and space conflicts are intended with these lines. */
07866    { "704", 9, 19, "9-19" },
07867    { "704", 9, 20, "9-20" },
07868    { "704", 8, 21, "8-21" },
07869 
07870    /* Add more spaces to ctx to test removing dead parking spaces. */
07871    { "705", 23, 25, "8-21,23-25" },
07872    { "706", 28, 31, "8-21,23-25,28-31" },
07873    { "707", 33, 34, "8-21,23-25,28-31,33-34" },
07874    { "708", 38, 40, "8-21,23-25,28-31,33-34,38-40" },
07875    { "709", 42, 43, "8-21,23-25,28-31,33-34,38-40,42-43" },
07876 };
07877 
07878 static const struct test_map test_new_ctx[] = {
07879    { "702", 4, 5, "4-5" },
07880    { "704", 24, 26, "4-5,24-26" },
07881    { "709", 29, 30, "4-5,24-26,29-30" },
07882    { "710", 32, 35, "4-5,24-26,29-30,32-35" },
07883    { "711", 37, 39, "4-5,24-26,29-30,32-35,37-39" },
07884 };
07885 #endif   /* defined(TEST_FRAMEWORK) */
07886 
07887 #if defined(TEST_FRAMEWORK)
07888 /*!
07889  * \internal
07890  * \brief Test parking dialplan usage map code.
07891  *
07892  * \param test Unit test context.
07893  *
07894  * \retval 0 on success.
07895  * \retval -1 on error.
07896  */
07897 static int test_dialplan_usage_map(struct ast_test *test)
07898 {
07899    struct parking_dp_context *old_ctx;
07900    struct parking_dp_context *new_ctx;
07901    struct ast_parkinglot *lot;
07902    struct parking_dp_spaces *spaces;
07903    struct parking_dp_space_map dead_spaces = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
07904    int res;
07905 
07906    ast_test_status_update(test, "Test parking dialplan usage map code\n");
07907 
07908    lot = create_parkinglot("test_lot");
07909    if (!lot) {
07910       return -1;
07911    }
07912    ast_copy_string(lot->cfg.parking_con, "test-ctx", sizeof(lot->cfg.parking_con));
07913    lot->cfg.parkext_exclusive = 1;
07914 
07915    ast_test_status_update(test,
07916       "Build old_ctx map\n");
07917    ast_log(LOG_NOTICE, "6 Ramp and space conflict warnings are expected.\n");
07918    old_ctx = test_build_maps(test, lot, "test_old_ctx", test_old_ctx,
07919       ARRAY_LEN(test_old_ctx));
07920    if (!old_ctx) {
07921       ao2_ref(lot, -1);
07922       return -1;
07923    }
07924 
07925    ast_test_status_update(test, "Build new_ctx map\n");
07926    new_ctx = test_build_maps(test, lot, "test_new_ctx", test_new_ctx,
07927       ARRAY_LEN(test_new_ctx));
07928    if (!new_ctx) {
07929       res = -1;
07930       goto fail_old_ctx;
07931    }
07932 
07933    ast_test_status_update(test, "Test removing dead parking spaces\n");
07934    remove_dead_spaces_usage((void *) &dead_spaces, &old_ctx->spaces,
07935       &new_ctx->spaces, test_add_dead_space);
07936    if (check_spaces(test, &dead_spaces, "8-21,23,28,31,40,42-43", "dead_spaces")) {
07937       res = -1;
07938       goto fail_dead_spaces;
07939    }
07940 
07941    res = 0;
07942 
07943 fail_dead_spaces:
07944    while ((spaces = AST_LIST_REMOVE_HEAD(&dead_spaces, node))) {
07945       ast_free(spaces);
07946    }
07947    destroy_dialplan_usage_context(new_ctx);
07948 
07949 fail_old_ctx:
07950    destroy_dialplan_usage_context(old_ctx);
07951    ao2_ref(lot, -1);
07952    return res;
07953 }
07954 #endif   /* defined(TEST_FRAMEWORK) */
07955 
07956 #if defined(TEST_FRAMEWORK)
07957 static int fake_fixup(struct ast_channel *clonechan, struct ast_channel *original)
07958 {
07959    return 0;
07960 }
07961 #endif   /* defined(TEST_FRAMEWORK) */
07962 
07963 #if defined(TEST_FRAMEWORK)
07964 static struct ast_channel *create_test_channel(const struct ast_channel_tech *fake_tech)
07965 {
07966    struct ast_channel *test_channel1;
07967 
07968    if (!(test_channel1 = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL,
07969       NULL, NULL, 0, 0, "TestChannel1"))) {
07970       ast_log(LOG_WARNING, "Whoa, test channel creation failed.\n");
07971       return NULL;
07972    }
07973 
07974    /* normally this is done in the channel driver */
07975    test_channel1->nativeformats = AST_FORMAT_GSM;
07976    test_channel1->writeformat = AST_FORMAT_GSM;
07977    test_channel1->rawwriteformat = AST_FORMAT_GSM;
07978    test_channel1->readformat = AST_FORMAT_GSM;
07979    test_channel1->rawreadformat = AST_FORMAT_GSM;
07980    test_channel1->tech = fake_tech;
07981 
07982    return test_channel1;
07983 }
07984 #endif   /* defined(TEST_FRAMEWORK) */
07985 
07986 #if defined(TEST_FRAMEWORK)
07987 static int unpark_test_channel(struct ast_channel *toremove, struct ast_park_call_args *args)
07988 {
07989    struct ast_context *con;
07990    struct parkeduser *pu_toremove;
07991    int res = 0;
07992 
07993    args->pu->notquiteyet = 1; /* go ahead and stop processing the test parking */
07994 
07995    AST_LIST_LOCK(&args->pu->parkinglot->parkings);
07996    AST_LIST_TRAVERSE_SAFE_BEGIN(&args->pu->parkinglot->parkings, pu_toremove, list) {
07997       if (pu_toremove == args->pu) {
07998          AST_LIST_REMOVE_CURRENT(list);
07999          break;
08000       }
08001    }
08002    AST_LIST_TRAVERSE_SAFE_END;
08003    AST_LIST_UNLOCK(&args->pu->parkinglot->parkings);
08004 
08005    if (!pu_toremove) {
08006       ast_log(LOG_WARNING, "Whoa, could not find parking test call!\n");
08007       return -1;
08008    }
08009 
08010    con = ast_context_find(args->pu->parkinglot->cfg.parking_con);
08011    if (con) {
08012       if (ast_context_remove_extension2(con, args->pu->parkingexten, 1, NULL, 0)) {
08013          ast_log(LOG_WARNING, "Whoa, failed to remove the parking extension!\n");
08014          res = -1;
08015       } else {
08016          notify_metermaids(args->pu->parkingexten,
08017             pu_toremove->parkinglot->cfg.parking_con, AST_DEVICE_NOT_INUSE);
08018       }
08019    } else {
08020       ast_log(LOG_WARNING, "Whoa, no parking context?\n");
08021       res = -1;
08022    }
08023 
08024    parkinglot_unref(pu_toremove->parkinglot);
08025    ast_free(pu_toremove);
08026    args->pu = NULL;
08027 
08028    if (!res && toremove) {
08029       ast_hangup(toremove);
08030    }
08031    return res;
08032 }
08033 #endif   /* defined(TEST_FRAMEWORK) */
08034 
08035 #if defined(TEST_FRAMEWORK)
08036 AST_TEST_DEFINE(features_test)
08037 {
08038    struct ast_channel *test_channel1 = NULL;
08039    struct ast_channel *parked_chan = NULL;
08040    struct ast_parkinglot *dynlot;
08041    struct ast_park_call_args args = {
08042       .timeout = DEFAULT_PARK_TIME,
08043    };
08044 
08045    int res = 0;
08046 
08047    static const struct ast_channel_tech fake_tech = {
08048       .fixup = fake_fixup, /* silence warning from masquerade */
08049    };
08050 
08051    static const char unique_lot_1[] = "myuniquetestparkinglot314";
08052    static const char unique_lot_2[] = "myuniquetestparkinglot3141592654";
08053    static const char unique_context_1[] = "myuniquetestcontext314";
08054    static const char unique_context_2[] = "myuniquetestcontext3141592654";
08055    static const char parkinglot_parkext[] = "750";
08056    static const char parkinglot_range[] = "751-760";
08057 
08058    switch (cmd) {
08059    case TEST_INIT:
08060       info->name = "features_test";
08061       info->category = "/main/features/";
08062       info->summary = "Features unit test";
08063       info->description =
08064          "Tests whether parking respects PARKINGLOT settings";
08065       return AST_TEST_NOT_RUN;
08066    case TEST_EXECUTE:
08067       break;
08068    }
08069 
08070    if (test_dialplan_usage_map(test)) {
08071       res = -1;
08072       goto exit_features_test;
08073    }
08074 
08075    /* changing a config option is a bad practice, but must be done in this case */
08076    parkeddynamic = 1;
08077 
08078    ast_test_status_update(test, "Test parking functionality with defaults\n");
08079    if (!(test_channel1 = create_test_channel(&fake_tech))) {
08080       res = -1;
08081       goto exit_features_test;
08082    }
08083    if (park_call_full(test_channel1, NULL, &args)) {
08084       res = -1;
08085       goto exit_features_test;
08086    }
08087    if (unpark_test_channel(test_channel1, &args)) {
08088       res = -1;
08089       goto exit_features_test;
08090    }
08091 
08092 
08093    ast_test_status_update(test, "Check that certain parking options are respected\n");
08094    if (!(test_channel1 = create_test_channel(&fake_tech))) {
08095       res = -1;
08096       goto exit_features_test;
08097    }
08098    pbx_builtin_setvar_helper(test_channel1, "PARKINGLOT", unique_lot_1);
08099    pbx_builtin_setvar_helper(test_channel1, "PARKINGDYNCONTEXT", unique_context_1);
08100    pbx_builtin_setvar_helper(test_channel1, "PARKINGDYNEXTEN", parkinglot_parkext);
08101    pbx_builtin_setvar_helper(test_channel1, "PARKINGDYNPOS", parkinglot_range);
08102    if (park_call_full(test_channel1, NULL, &args)) {
08103       res = -1;
08104       goto exit_features_test;
08105    }
08106    /* grab newly created parking lot for destruction in the end */
08107    dynlot = args.pu->parkinglot;
08108    if (args.pu->parkingnum != 751
08109       || strcmp(dynlot->name, unique_lot_1)
08110       || strcmp(dynlot->cfg.parking_con, unique_context_1)
08111       || strcmp(dynlot->cfg.parkext, parkinglot_parkext)
08112       || dynlot->cfg.parking_start != 751
08113       || dynlot->cfg.parking_stop != 760) {
08114       ast_test_status_update(test, "Parking settings were not respected\n");
08115       ast_test_status_update(test, "Dyn-name:%s\n", dynlot->name);
08116       ast_test_status_update(test, "Dyn-context:%s\n", dynlot->cfg.parking_con);
08117       ast_test_status_update(test, "Dyn-parkext:%s\n", dynlot->cfg.parkext);
08118       ast_test_status_update(test, "Dyn-parkpos:%d-%d\n", dynlot->cfg.parking_start,
08119          dynlot->cfg.parking_stop);
08120       ast_test_status_update(test, "Parked in space:%d\n", args.pu->parkingnum);
08121       if (!unpark_test_channel(test_channel1, &args)) {
08122          test_channel1 = NULL;
08123       }
08124       res = -1;
08125       goto exit_features_test;
08126    } else {
08127       ast_test_status_update(test, "Parking settings for non-masquerading park verified\n");
08128    }
08129    if (unpark_test_channel(test_channel1, &args)) {
08130       res = -1;
08131       goto exit_features_test;
08132    }
08133 
08134 
08135    ast_test_status_update(test, "Check #2 that certain parking options are respected\n");
08136    if (!(test_channel1 = create_test_channel(&fake_tech))) {
08137       res = -1;
08138       goto exit_features_test;
08139    }
08140    pbx_builtin_setvar_helper(test_channel1, "PARKINGLOT", unique_lot_2);
08141    pbx_builtin_setvar_helper(test_channel1, "PARKINGDYNCONTEXT", unique_context_2);
08142    pbx_builtin_setvar_helper(test_channel1, "PARKINGDYNEXTEN", parkinglot_parkext);
08143    pbx_builtin_setvar_helper(test_channel1, "PARKINGDYNPOS", parkinglot_range);
08144    if (masq_park_call(test_channel1, NULL, &args)) {
08145       res = -1;
08146       goto exit_features_test;
08147    }
08148    /* hangup zombie channel */
08149    ast_hangup(test_channel1);
08150    test_channel1 = NULL;
08151 
08152    dynlot = args.pu->parkinglot;
08153    if (args.pu->parkingnum != 751
08154       || strcmp(dynlot->name, unique_lot_2)
08155       || strcmp(dynlot->cfg.parking_con, unique_context_2)
08156       || strcmp(dynlot->cfg.parkext, parkinglot_parkext)
08157       || dynlot->cfg.parking_start != 751
08158       || dynlot->cfg.parking_stop != 760) {
08159       ast_test_status_update(test, "Parking settings were not respected\n");
08160       ast_test_status_update(test, "Dyn-name:%s\n", dynlot->name);
08161       ast_test_status_update(test, "Dyn-context:%s\n", dynlot->cfg.parking_con);
08162       ast_test_status_update(test, "Dyn-parkext:%s\n", dynlot->cfg.parkext);
08163       ast_test_status_update(test, "Dyn-parkpos:%d-%d\n", dynlot->cfg.parking_start,
08164          dynlot->cfg.parking_stop);
08165       ast_test_status_update(test, "Parked in space:%d\n", args.pu->parkingnum);
08166       res = -1;
08167    } else {
08168       ast_test_status_update(test, "Parking settings for masquerading park verified\n");
08169    }
08170 
08171    /* find the real channel */
08172    parked_chan = ast_channel_get_by_name("TestChannel1");
08173    if (unpark_test_channel(parked_chan, &args)) {
08174       if (parked_chan) {
08175          ast_hangup(parked_chan);
08176       }
08177       res = -1;
08178    }
08179 
08180 
08181 exit_features_test:
08182 
08183    if (test_channel1) {
08184       ast_hangup(test_channel1);
08185    }
08186 
08187    force_reload_load = 1;
08188    ast_features_reload();
08189    return res ? AST_TEST_FAIL : AST_TEST_PASS;
08190 }
08191 #endif   /* defined(TEST_FRAMEWORK) */
08192 
08193 int ast_features_init(void)
08194 {
08195    int res;
08196 
08197    parkinglots = ao2_container_alloc(7, parkinglot_hash_cb, parkinglot_cmp_cb);
08198    if (!parkinglots) {
08199       return -1;
08200    }
08201 
08202    res = load_config(0);
08203    if (res) {
08204       return res;
08205    }
08206    ast_cli_register_multiple(cli_features, ARRAY_LEN(cli_features));
08207    if (ast_pthread_create(&parking_thread, NULL, do_parking_thread, NULL)) {
08208       return -1;
08209    }
08210    ast_register_application2(app_bridge, bridge_exec, NULL, NULL, NULL);
08211    res = ast_register_application2(parkedcall, parked_call_exec, NULL, NULL, NULL);
08212    if (!res)
08213       res = ast_register_application2(parkcall, park_call_exec, NULL, NULL, NULL);
08214    if (!res) {
08215       ast_manager_register_xml("ParkedCalls", 0, manager_parking_status);
08216       ast_manager_register_xml("Park", EVENT_FLAG_CALL, manager_park);
08217       ast_manager_register_xml("Bridge", EVENT_FLAG_CALL, action_bridge);
08218    }
08219 
08220    res |= ast_devstate_prov_add("Park", metermaidstate);
08221 #if defined(TEST_FRAMEWORK)
08222    res |= AST_TEST_REGISTER(features_test);
08223 #endif   /* defined(TEST_FRAMEWORK) */
08224 
08225    return res;
08226 }

Generated on 30 Aug 2012 for Asterisk - The Open Source Telephony Project by  doxygen 1.6.1