Fri Jul 3 20:35:39 2009

Asterisk developer's documentation


res_features.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, 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         <depend>chan_local</depend>
00028  ***/
00029 
00030 #include "asterisk.h"
00031 
00032 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
00033 
00034 #include <pthread.h>
00035 #include <stdlib.h>
00036 #include <errno.h>
00037 #include <unistd.h>
00038 #include <string.h>
00039 #include <stdlib.h>
00040 #include <stdio.h>
00041 #include <sys/time.h>
00042 #include <sys/signal.h>
00043 #include <netinet/in.h>
00044 
00045 #include "asterisk/lock.h"
00046 #include "asterisk/file.h"
00047 #include "asterisk/logger.h"
00048 #include "asterisk/channel.h"
00049 #include "asterisk/pbx.h"
00050 #include "asterisk/options.h"
00051 #include "asterisk/causes.h"
00052 #include "asterisk/module.h"
00053 #include "asterisk/translate.h"
00054 #include "asterisk/app.h"
00055 #include "asterisk/say.h"
00056 #include "asterisk/features.h"
00057 #include "asterisk/musiconhold.h"
00058 #include "asterisk/config.h"
00059 #include "asterisk/cli.h"
00060 #include "asterisk/manager.h"
00061 #include "asterisk/utils.h"
00062 #include "asterisk/adsi.h"
00063 #include "asterisk/devicestate.h"
00064 #include "asterisk/monitor.h"
00065 #include "asterisk/global_datastores.h"
00066 
00067 #define DEFAULT_PARK_TIME 45000
00068 #define DEFAULT_TRANSFER_DIGIT_TIMEOUT 3000
00069 #define DEFAULT_FEATURE_DIGIT_TIMEOUT 500
00070 #define DEFAULT_NOANSWER_TIMEOUT_ATTENDED_TRANSFER 15000
00071 
00072 #define AST_MAX_WATCHERS 256
00073 
00074 enum {
00075    AST_FEATURE_FLAG_NEEDSDTMF = (1 << 0),
00076    AST_FEATURE_FLAG_ONPEER =    (1 << 1),
00077    AST_FEATURE_FLAG_ONSELF =    (1 << 2),
00078    AST_FEATURE_FLAG_BYCALLEE =  (1 << 3),
00079    AST_FEATURE_FLAG_BYCALLER =  (1 << 4),
00080    AST_FEATURE_FLAG_BYBOTH  =   (3 << 3),
00081 };
00082 
00083 static char *parkedcall = "ParkedCall";
00084 
00085 static int parkaddhints = 0;                               /*!< Add parking hints automatically */
00086 static int parkingtime = DEFAULT_PARK_TIME;                /*!< No more than 45 seconds parked before you do something with them */
00087 static char parking_con[AST_MAX_EXTENSION];                /*!< Context for which parking is made accessible */
00088 static char parking_con_dial[AST_MAX_EXTENSION];           /*!< Context for dialback for parking (KLUDGE) */
00089 static char parking_ext[AST_MAX_EXTENSION];                /*!< Extension you type to park the call */
00090 static char pickup_ext[AST_MAX_EXTENSION];                 /*!< Call pickup extension */
00091 static char parkmohclass[MAX_MUSICCLASS];                  /*!< Music class used for parking */
00092 static int parking_start;                                  /*!< First available extension for parking */
00093 static int parking_stop;                                   /*!< Last available extension for parking */
00094 
00095 static int parkedcalltransfers;                            /*!< Who can REDIRECT after picking up a parked a call */
00096 
00097 static char courtesytone[256];                             /*!< Courtesy tone */
00098 static int parkedplay = 0;                                 /*!< Who to play the courtesy tone to */
00099 static char xfersound[256];                                /*!< Call transfer sound */
00100 static char xferfailsound[256];                            /*!< Call transfer failure sound */
00101 
00102 static int parking_offset;
00103 static int parkfindnext;
00104 
00105 static int adsipark;
00106 
00107 static int transferdigittimeout;
00108 static int featuredigittimeout;
00109 
00110 static int atxfernoanswertimeout;
00111 
00112 static char *registrar = "res_features";        /*!< Registrar for operations */
00113 
00114 /* module and CLI command definitions */
00115 static char *synopsis = "Answer a parked call";
00116 
00117 static char *descrip = "ParkedCall(exten):"
00118 "Used to connect to a parked call.  This application is always\n"
00119 "registered internally and does not need to be explicitly added\n"
00120 "into the dialplan, although you should include the 'parkedcalls'\n"
00121 "context.\n";
00122 
00123 static char *parkcall = PARK_APP_NAME;
00124 
00125 static char *synopsis2 = "Park yourself";
00126 
00127 static char *descrip2 = "Park():"
00128 "Used to park yourself (typically in combination with a supervised\n"
00129 "transfer to know the parking space). This application is always\n"
00130 "registered internally and does not need to be explicitly added\n"
00131 "into the dialplan, although you should include the 'parkedcalls'\n"
00132 "context (or the context specified in features.conf).\n\n"
00133 "If you set the PARKINGEXTEN variable to an extension in your\n"
00134 "parking context, park() will park the call on that extension, unless\n"
00135 "it already exists. In that case, execution will continue at next\n"
00136 "priority.\n" ;
00137 
00138 static struct ast_app *monitor_app = NULL;
00139 static int monitor_ok = 1;
00140 
00141 struct parkeduser {
00142    struct ast_channel *chan;                   /*!< Parking channel */
00143    struct timeval start;                       /*!< Time the parking started */
00144    int parkingnum;                             /*!< Parking lot */
00145    char parkingexten[AST_MAX_EXTENSION];       /*!< If set beforehand, parking extension used for this call */
00146    char context[AST_MAX_CONTEXT];              /*!< Where to go if our parking time expires */
00147    char exten[AST_MAX_EXTENSION];
00148    int priority;
00149    int parkingtime;                            /*!< Maximum length in parking lot before return */
00150    int notquiteyet;
00151    char peername[1024];
00152    unsigned char moh_trys;
00153    struct parkeduser *next;
00154 };
00155 
00156 static struct parkeduser *parkinglot;
00157 
00158 AST_MUTEX_DEFINE_STATIC(parking_lock); /*!< protects all static variables above */
00159 
00160 static pthread_t parking_thread;
00161 
00162 char *ast_parking_ext(void)
00163 {
00164    return parking_ext;
00165 }
00166 
00167 char *ast_pickup_ext(void)
00168 {
00169    return pickup_ext;
00170 }
00171 
00172 struct ast_bridge_thread_obj 
00173 {
00174    struct ast_bridge_config bconfig;
00175    struct ast_channel *chan;
00176    struct ast_channel *peer;
00177    unsigned int return_to_pbx:1;
00178 };
00179 
00180 
00181 
00182 /*! \brief store context, priority and extension */
00183 static void set_c_e_p(struct ast_channel *chan, const char *context, const char *ext, int pri)
00184 {
00185    ast_copy_string(chan->context, context, sizeof(chan->context));
00186    ast_copy_string(chan->exten, ext, sizeof(chan->exten));
00187    chan->priority = pri;
00188 }
00189 
00190 static void check_goto_on_transfer(struct ast_channel *chan) 
00191 {
00192    struct ast_channel *xferchan;
00193    const char *val = pbx_builtin_getvar_helper(chan, "GOTO_ON_BLINDXFR");
00194    char *x, *goto_on_transfer;
00195    struct ast_frame *f;
00196 
00197    if (ast_strlen_zero(val))
00198       return;
00199 
00200    goto_on_transfer = ast_strdupa(val);
00201 
00202    if (!(xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, "%s", chan->name)))
00203       return;
00204 
00205    for (x = goto_on_transfer; x && *x; x++) {
00206       if (*x == '^')
00207          *x = '|';
00208    }
00209    /* Make formats okay */
00210    xferchan->readformat = chan->readformat;
00211    xferchan->writeformat = chan->writeformat;
00212    ast_channel_masquerade(xferchan, chan);
00213    ast_parseable_goto(xferchan, goto_on_transfer);
00214    xferchan->_state = AST_STATE_UP;
00215    ast_clear_flag(xferchan, AST_FLAGS_ALL);  
00216    xferchan->_softhangup = 0;
00217    if ((f = ast_read(xferchan))) {
00218       ast_frfree(f);
00219       f = NULL;
00220       ast_pbx_start(xferchan);
00221    } else {
00222       ast_hangup(xferchan);
00223    }
00224 }
00225 
00226 static struct ast_channel *ast_feature_request_and_dial(struct ast_channel *caller, const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name, const char *language);
00227 
00228 
00229 static void *ast_bridge_call_thread(void *data) 
00230 {
00231    struct ast_bridge_thread_obj *tobj = data;
00232    int res;
00233 
00234    tobj->chan->appl = !tobj->return_to_pbx ? "Transferred Call" : "ManagerBridge";
00235    tobj->chan->data = tobj->peer->name;
00236    tobj->peer->appl = !tobj->return_to_pbx ? "Transferred Call" : "ManagerBridge";
00237    tobj->peer->data = tobj->chan->name;
00238 
00239    ast_bridge_call(tobj->peer, tobj->chan, &tobj->bconfig);
00240 
00241    if (tobj->return_to_pbx) {
00242       if (!ast_check_hangup(tobj->peer)) {
00243          ast_log(LOG_VERBOSE, "putting peer %s into PBX again\n", tobj->peer->name);
00244          res = ast_pbx_start(tobj->peer);
00245          if (res != AST_PBX_SUCCESS)
00246             ast_log(LOG_WARNING, "FAILED continuing PBX on peer %s\n", tobj->peer->name);
00247       } else
00248          ast_hangup(tobj->peer);
00249       if (!ast_check_hangup(tobj->chan)) {
00250          ast_log(LOG_VERBOSE, "putting chan %s into PBX again\n", tobj->chan->name);
00251          res = ast_pbx_start(tobj->chan);
00252          if (res != AST_PBX_SUCCESS)
00253             ast_log(LOG_WARNING, "FAILED continuing PBX on chan %s\n", tobj->chan->name);
00254       } else
00255          ast_hangup(tobj->chan);
00256    } else {
00257       ast_hangup(tobj->chan);
00258       ast_hangup(tobj->peer);
00259    }
00260 
00261    free(tobj);
00262 
00263    return NULL;
00264 }
00265 
00266 static void ast_bridge_call_thread_launch(void *data) 
00267 {
00268    pthread_t thread;
00269    pthread_attr_t attr;
00270    struct sched_param sched;
00271 
00272    pthread_attr_init(&attr);
00273    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
00274    ast_pthread_create(&thread, &attr,ast_bridge_call_thread, data);
00275    pthread_attr_destroy(&attr);
00276    memset(&sched, 0, sizeof(sched));
00277    pthread_setschedparam(thread, SCHED_RR, &sched);
00278 }
00279 
00280 static int adsi_announce_park(struct ast_channel *chan, char *parkingexten)
00281 {
00282    int res;
00283    int justify[5] = {ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT};
00284    char tmp[256];
00285    char *message[5] = {NULL, NULL, NULL, NULL, NULL};
00286 
00287    snprintf(tmp, sizeof(tmp), "Parked on %s", parkingexten);
00288    message[0] = tmp;
00289    res = ast_adsi_load_session(chan, NULL, 0, 1);
00290    if (res == -1)
00291       return res;
00292    return ast_adsi_print(chan, message, justify, 1);
00293 }
00294 
00295 /*! \brief Notify metermaids that we've changed an extension */
00296 static void notify_metermaids(char *exten, char *context)
00297 {
00298    if (option_debug > 3)
00299       ast_log(LOG_DEBUG, "Notification of state change to metermaids %s@%s\n", exten, context);
00300 
00301    /* Send notification to devicestate subsystem */
00302    ast_device_state_changed("park:%s@%s", exten, context);
00303    return;
00304 }
00305 
00306 /*! \brief metermaids callback from devicestate.c */
00307 static int metermaidstate(const char *data)
00308 {
00309    int res = AST_DEVICE_INVALID;
00310    char *context = ast_strdupa(data);
00311    char *exten;
00312 
00313    exten = strsep(&context, "@");
00314    if (!context)
00315       return res;
00316    
00317    if (option_debug > 3)
00318       ast_log(LOG_DEBUG, "Checking state of exten %s in context %s\n", exten, context);
00319 
00320    res = ast_exists_extension(NULL, context, exten, 1, NULL);
00321 
00322    if (!res)
00323       return AST_DEVICE_NOT_INUSE;
00324    else
00325       return AST_DEVICE_INUSE;
00326 }
00327 
00328 static int park_call_full(struct ast_channel *chan, struct ast_channel *peer, int timeout, int *extout, char *orig_chan_name)
00329 {
00330    struct parkeduser *pu, *cur;
00331    int i, x = -1, parking_range, parkingnum_copy;
00332    struct ast_context *con;
00333    const char *parkingexten;
00334    
00335    /* Allocate memory for parking data */
00336    if (!(pu = ast_calloc(1, sizeof(*pu)))) 
00337       return -1;
00338 
00339    /* Lock parking lot */
00340    ast_mutex_lock(&parking_lock);
00341    /* Check for channel variable PARKINGEXTEN */
00342    parkingexten = pbx_builtin_getvar_helper(chan, "PARKINGEXTEN");
00343    if (!ast_strlen_zero(parkingexten)) {
00344       /*!\note The API forces us to specify a numeric parking slot, even
00345        * though the architecture would tend to support non-numeric extensions
00346        * (as are possible with SIP, for example).  Hence, we enforce that
00347        * limitation here.  If extout was not numeric, we could permit
00348        * arbitrary non-numeric extensions.
00349        */
00350       if (sscanf(parkingexten, "%d", &x) != 1 || x < 0) {
00351          ast_log(LOG_WARNING, "PARKINGEXTEN does not indicate a valid parking slot: '%s'.\n", parkingexten);
00352          ast_mutex_unlock(&parking_lock);
00353          free(pu);
00354          return 1;   /* Continue execution if possible */
00355       }
00356       snprintf(pu->parkingexten, sizeof(pu->parkingexten), "%d", x);
00357 
00358       if (ast_exists_extension(NULL, parking_con, pu->parkingexten, 1, NULL)) {
00359          ast_mutex_unlock(&parking_lock);
00360          free(pu);
00361          ast_log(LOG_WARNING, "Requested parking extension already exists: %s@%s\n", parkingexten, parking_con);
00362          return 1;   /* Continue execution if possible */
00363       }
00364    } else {
00365       /* Select parking space within range */
00366       parking_range = parking_stop - parking_start+1;
00367       for (i = 0; i < parking_range; i++) {
00368          x = (i + parking_offset) % parking_range + parking_start;
00369          cur = parkinglot;
00370          while(cur) {
00371             if (cur->parkingnum == x) 
00372                break;
00373             cur = cur->next;
00374          }
00375          if (!cur)
00376             break;
00377       }
00378 
00379       if (!(i < parking_range)) {
00380          ast_log(LOG_WARNING, "No more parking spaces\n");
00381          free(pu);
00382          ast_mutex_unlock(&parking_lock);
00383          return -1;
00384       }
00385       /* Set pointer for next parking */
00386       if (parkfindnext) 
00387          parking_offset = x - parking_start + 1;
00388       snprintf(pu->parkingexten, sizeof(pu->parkingexten), "%d", x);
00389    }
00390    
00391    chan->appl = "Parked Call";
00392    chan->data = NULL; 
00393 
00394    pu->chan = chan;
00395    
00396    /* Put the parked channel on hold if we have two different channels */
00397    if (chan != peer) {
00398       ast_indicate_data(pu->chan, AST_CONTROL_HOLD, 
00399          S_OR(parkmohclass, NULL),
00400          !ast_strlen_zero(parkmohclass) ? strlen(parkmohclass) + 1 : 0);
00401    }
00402    
00403    pu->start = ast_tvnow();
00404    pu->parkingnum = x;
00405    pu->parkingtime = (timeout > 0) ? timeout : parkingtime;
00406    if (extout)
00407       *extout = x;
00408 
00409    if (peer) { 
00410       /* This is so ugly that it hurts, but implementing get_base_channel() on local channels
00411          could have ugly side effects.  We could have transferer<->local,1<->local,2<->parking
00412          and we need the callback name to be that of transferer.  Since local,1/2 have the same
00413          name we can be tricky and just grab the bridged channel from the other side of the local
00414       */
00415       if (!strcasecmp(peer->tech->type, "Local")) {
00416          struct ast_channel *tmpchan, *base_peer;
00417          char other_side[AST_CHANNEL_NAME];
00418          char *c;
00419          ast_copy_string(other_side, peer->name, sizeof(other_side));
00420          if ((c = strrchr(other_side, ','))) {
00421             *++c = '1';
00422          }
00423          if ((tmpchan = ast_get_channel_by_name_locked(other_side))) {
00424             if ((base_peer = ast_bridged_channel(tmpchan))) {
00425                ast_copy_string(pu->peername, base_peer->name, sizeof(pu->peername));
00426             }
00427             ast_channel_unlock(tmpchan);
00428          }
00429       } else {
00430          ast_copy_string(pu->peername, peer->name, sizeof(pu->peername));
00431       }
00432    }
00433 
00434    /* Remember what had been dialed, so that if the parking
00435       expires, we try to come back to the same place */
00436    ast_copy_string(pu->context, S_OR(chan->macrocontext, chan->context), sizeof(pu->context));
00437    ast_copy_string(pu->exten, S_OR(chan->macroexten, chan->exten), sizeof(pu->exten));
00438    pu->priority = chan->macropriority ? chan->macropriority : chan->priority;
00439    pu->next = parkinglot;
00440    parkinglot = pu;
00441    parkingnum_copy = pu->parkingnum;
00442    /* If parking a channel directly, don't quite yet get parking running on it */
00443    if (peer == chan) 
00444       pu->notquiteyet = 1;
00445 
00446    if (option_verbose > 1) 
00447       ast_verbose(VERBOSE_PREFIX_2 "Parked %s on %d@%s. Will timeout back to extension [%s] %s, %d in %d seconds\n", pu->chan->name, pu->parkingnum, parking_con, pu->context, pu->exten, pu->priority, (pu->parkingtime/1000));
00448 
00449    manager_event(EVENT_FLAG_CALL, "ParkedCall",
00450       "Exten: %s\r\n"
00451       "Channel: %s\r\n"
00452       "From: %s\r\n"
00453       "Timeout: %ld\r\n"
00454       "CallerID: %s\r\n"
00455       "CallerIDName: %s\r\n",
00456       pu->parkingexten, pu->chan->name, peer ? peer->name : "",
00457       (long)pu->start.tv_sec + (long)(pu->parkingtime/1000) - (long)time(NULL),
00458       S_OR(pu->chan->cid.cid_num, "<unknown>"),
00459       S_OR(pu->chan->cid.cid_name, "<unknown>")
00460       );
00461 
00462    if (peer && adsipark && ast_adsi_available(peer)) {
00463       adsi_announce_park(peer, pu->parkingexten);  /* Only supports parking numbers */
00464       ast_adsi_unload_session(peer);
00465    }
00466 
00467    con = ast_context_find(parking_con);
00468    if (!con) 
00469       con = ast_context_create(NULL, parking_con, registrar);
00470    if (!con)   /* Still no context? Bad */
00471       ast_log(LOG_ERROR, "Parking context '%s' does not exist and unable to create\n", parking_con);
00472    if (con) {
00473       if (!ast_add_extension2(con, 1, pu->parkingexten, 1, NULL, NULL, parkedcall, strdup(pu->parkingexten), ast_free, registrar)) {
00474          notify_metermaids(pu->parkingexten, parking_con);
00475       }
00476    }
00477 
00478    ast_mutex_unlock(&parking_lock);
00479    /* Wake up the (presumably select()ing) thread */
00480    pthread_kill(parking_thread, SIGURG);
00481 
00482    /* Only say number if it's a number and the channel hasn't been masqueraded away */
00483    if (peer && (ast_strlen_zero(orig_chan_name) || !strcasecmp(peer->name, orig_chan_name))) {
00484       /* Make sure we don't start saying digits to the channel being parked */
00485       ast_set_flag(peer, AST_FLAG_MASQ_NOSTREAM);
00486       /* Tell the peer channel the number of the parking space */
00487       ast_say_digits(peer, parkingnum_copy, "", peer->language);
00488       ast_clear_flag(peer, AST_FLAG_MASQ_NOSTREAM);
00489    }
00490 
00491    if (peer == chan) { /* pu->notquiteyet = 1 */
00492       /* Wake up parking thread if we're really done */
00493       ast_indicate_data(pu->chan, AST_CONTROL_HOLD, 
00494          S_OR(parkmohclass, NULL),
00495          !ast_strlen_zero(parkmohclass) ? strlen(parkmohclass) + 1 : 0);
00496       pu->notquiteyet = 0;
00497       pthread_kill(parking_thread, SIGURG);
00498    }
00499    return 0;
00500 }
00501 
00502 /*! \brief Park a call 
00503    \note We put the user in the parking list, then wake up the parking thread to be sure it looks
00504    after these channels too */
00505 int ast_park_call(struct ast_channel *chan, struct ast_channel *peer, int timeout, int *extout)
00506 {
00507    return park_call_full(chan, peer, timeout, extout, NULL);
00508 }
00509 
00510 static int masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout, int play_announcement)
00511 {
00512    struct ast_channel *chan;
00513    struct ast_frame *f;
00514    char *orig_chan_name = NULL;
00515    int park_status;
00516 
00517    /* Make a new, fake channel that we'll use to masquerade in the real one */
00518    if (!(chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, rchan->accountcode, rchan->exten, rchan->context, rchan->amaflags, "Parked/%s",rchan->name))) {
00519       ast_log(LOG_WARNING, "Unable to create parked channel\n");
00520       return -1;
00521    }
00522 
00523    /* Make formats okay */
00524    chan->readformat = rchan->readformat;
00525    chan->writeformat = rchan->writeformat;
00526    ast_channel_masquerade(chan, rchan);
00527 
00528    /* Setup the extensions and such */
00529    set_c_e_p(chan, rchan->context, rchan->exten, rchan->priority);
00530 
00531    /* Make the masq execute */
00532    if ((f = ast_read(chan))) {
00533       ast_frfree(f);
00534    }
00535 
00536    if (!play_announcement) {
00537       orig_chan_name = ast_strdupa(chan->name);
00538    }
00539 
00540    park_status = park_call_full(chan, peer, timeout, extout, orig_chan_name);
00541    if (park_status == 1) {
00542       /* would be nice to play: "invalid parking extension" */
00543       ast_hangup(chan);
00544       return -1;
00545    }
00546 
00547    return 0;
00548 }
00549 
00550 int ast_masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout)
00551 {
00552    return masq_park_call(rchan, peer, timeout, extout, 0);
00553 }
00554 
00555 static int masq_park_call_announce(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout)
00556 {
00557    return masq_park_call(rchan, peer, timeout, extout, 1);
00558 }
00559 
00560 #define FEATURE_RETURN_HANGUP                  -1
00561 #define FEATURE_RETURN_SUCCESSBREAK             0
00562 #define FEATURE_RETURN_PBX_KEEPALIVE            AST_PBX_KEEPALIVE
00563 #define FEATURE_RETURN_NO_HANGUP_PEER           AST_PBX_NO_HANGUP_PEER
00564 #define FEATURE_RETURN_NO_HANGUP_PEER_PARKED    AST_PBX_NO_HANGUP_PEER_PARKED
00565 #define FEATURE_RETURN_PASSDIGITS               21
00566 #define FEATURE_RETURN_STOREDIGITS              22
00567 #define FEATURE_RETURN_SUCCESS                  23
00568 #define FEATURE_RETURN_KEEPTRYING               24
00569 
00570 #define FEATURE_SENSE_CHAN (1 << 0)
00571 #define FEATURE_SENSE_PEER (1 << 1)
00572 
00573 /*! \brief
00574  * set caller and callee according to the direction
00575  */
00576 static void set_peers(struct ast_channel **caller, struct ast_channel **callee,
00577    struct ast_channel *peer, struct ast_channel *chan, int sense)
00578 {
00579    if (sense == FEATURE_SENSE_PEER) {
00580       *caller = peer;
00581       *callee = chan;
00582    } else {
00583       *callee = peer;
00584       *caller = chan;
00585    }
00586 }
00587 
00588 /*! \brief support routing for one touch call parking */
00589 static int builtin_parkcall(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense, void *data)
00590 {
00591    struct ast_channel *parker;
00592    struct ast_channel *parkee;
00593    int res = 0;
00594    struct ast_module_user *u;
00595 
00596    u = ast_module_user_add(chan);
00597 
00598    set_peers(&parker, &parkee, peer, chan, sense);
00599    /* Setup the exten/priority to be s/1 since we don't know
00600       where this call should return */
00601    strcpy(chan->exten, "s");
00602    chan->priority = 1;
00603    if (chan->_state != AST_STATE_UP)
00604       res = ast_answer(chan);
00605    if (!res)
00606       res = ast_safe_sleep(chan, 1000);
00607 
00608    if (!res) {
00609       if (sense == FEATURE_SENSE_CHAN) {
00610          res = ast_park_call(parkee, parker, 0, NULL);
00611          if (!res) {
00612             if (sense == FEATURE_SENSE_CHAN) {
00613                res = AST_PBX_NO_HANGUP_PEER_PARKED;
00614             } else {
00615                res = AST_PBX_KEEPALIVE;
00616             }
00617          }
00618       }
00619       else if (sense == FEATURE_SENSE_PEER) {
00620          masq_park_call_announce(parkee, parker, 0, NULL);
00621          res = 0; /* PBX should hangup zombie channel */
00622       }
00623    }
00624 
00625    ast_module_user_remove(u);
00626    return res;
00627 
00628 }
00629 
00630 static int builtin_automonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense, void *data)
00631 {
00632    char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
00633    int x = 0;
00634    size_t len;
00635    struct ast_channel *caller_chan, *callee_chan;
00636 
00637    if (!monitor_ok) {
00638       ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
00639       return -1;
00640    }
00641 
00642    if (!monitor_app && !(monitor_app = pbx_findapp("Monitor"))) {
00643       monitor_ok = 0;
00644       ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
00645       return -1;
00646    }
00647 
00648    set_peers(&caller_chan, &callee_chan, peer, chan, sense);
00649 
00650    if (!ast_strlen_zero(courtesytone)) {
00651       if (ast_autoservice_start(callee_chan))
00652          return -1;
00653       if (ast_stream_and_wait(caller_chan, courtesytone, caller_chan->language, "")) {
00654          ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
00655          ast_autoservice_stop(callee_chan);
00656          return -1;
00657       }
00658       if (ast_autoservice_stop(callee_chan))
00659          return -1;
00660    }
00661    
00662    if (callee_chan->monitor) {
00663       if (option_verbose > 3)
00664          ast_verbose(VERBOSE_PREFIX_3 "User hit '%s' to stop recording call.\n", code);
00665       ast_monitor_stop(callee_chan, 1);
00666       return FEATURE_RETURN_SUCCESS;
00667    }
00668 
00669    if (caller_chan && callee_chan) {
00670       const char *touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_FORMAT");
00671       const char *touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR");
00672 
00673       if (!touch_format)
00674          touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_FORMAT");
00675 
00676       if (!touch_monitor)
00677          touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR");
00678    
00679       if (touch_monitor) {
00680          len = strlen(touch_monitor) + 50;
00681          args = alloca(len);
00682          touch_filename = alloca(len);
00683          snprintf(touch_filename, len, "auto-%ld-%s", (long)time(NULL), touch_monitor);
00684          snprintf(args, len, "%s|%s|m", (touch_format) ? touch_format : "wav", touch_filename);
00685       } else {
00686          caller_chan_id = ast_strdupa(S_OR(caller_chan->cid.cid_num, caller_chan->name));
00687          callee_chan_id = ast_strdupa(S_OR(callee_chan->cid.cid_num, callee_chan->name));
00688          len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
00689          args = alloca(len);
00690          touch_filename = alloca(len);
00691          snprintf(touch_filename, len, "auto-%ld-%s-%s", (long)time(NULL), caller_chan_id, callee_chan_id);
00692          snprintf(args, len, "%s|%s|m", S_OR(touch_format, "wav"), touch_filename);
00693       }
00694 
00695       for(x = 0; x < strlen(args); x++) {
00696          if (args[x] == '/')
00697             args[x] = '-';
00698       }
00699       
00700       if (option_verbose > 3)
00701          ast_verbose(VERBOSE_PREFIX_3 "User hit '%s' to record call. filename: %s\n", code, args);
00702 
00703       pbx_exec(callee_chan, monitor_app, args);
00704       pbx_builtin_setvar_helper(callee_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
00705       pbx_builtin_setvar_helper(caller_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
00706    
00707       return FEATURE_RETURN_SUCCESS;
00708    }
00709    
00710    ast_log(LOG_NOTICE,"Cannot record the call. One or both channels have gone away.\n");  
00711    return -1;
00712 }
00713 
00714 static int builtin_disconnect(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense, void *data)
00715 {
00716    if (option_verbose > 3)
00717       ast_verbose(VERBOSE_PREFIX_3 "User hit '%s' to disconnect call.\n", code);
00718    return FEATURE_RETURN_HANGUP;
00719 }
00720 
00721 static int finishup(struct ast_channel *chan)
00722 {
00723         ast_indicate(chan, AST_CONTROL_UNHOLD);
00724   
00725         return ast_autoservice_stop(chan);
00726 }
00727 
00728 /*! \brief Find the context for the transfer */
00729 static const char *real_ctx(struct ast_channel *transferer, struct ast_channel *transferee)
00730 {
00731         const char *s = pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT");
00732         if (ast_strlen_zero(s))
00733                 s = pbx_builtin_getvar_helper(transferee, "TRANSFER_CONTEXT");
00734         if (ast_strlen_zero(s)) /* Use the non-macro context to transfer the call XXX ? */
00735                 s = transferer->macrocontext;
00736         if (ast_strlen_zero(s))
00737                 s = transferer->context;
00738         return s;  
00739 }
00740 
00741 static int builtin_blindtransfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense, void *data)
00742 {
00743    struct ast_channel *transferer;
00744    struct ast_channel *transferee;
00745    const char *transferer_real_context;
00746    char xferto[256];
00747    int res;
00748 
00749    set_peers(&transferer, &transferee, peer, chan, sense);
00750    transferer_real_context = real_ctx(transferer, transferee);
00751    /* Start autoservice on chan while we talk to the originator */
00752    ast_autoservice_start(transferee);
00753    ast_indicate(transferee, AST_CONTROL_HOLD);
00754 
00755    memset(xferto, 0, sizeof(xferto));
00756    
00757    /* Transfer */
00758    res = ast_stream_and_wait(transferer, "pbx-transfer", transferer->language, AST_DIGIT_ANY);
00759    if (res < 0) {
00760       finishup(transferee);
00761       return -1; /* error ? */
00762    }
00763    if (res > 0)   /* If they've typed a digit already, handle it */
00764       xferto[0] = (char) res;
00765 
00766    ast_stopstream(transferer);
00767    res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
00768    if (res < 0) {  /* hangup, would be 0 for invalid and 1 for valid */
00769       finishup(transferee);
00770       return res;
00771    }
00772    if (!strcmp(xferto, ast_parking_ext())) {
00773       res = finishup(transferee);
00774       if (res)
00775          res = -1;
00776       else if (!masq_park_call_announce(transferee, transferer, 0, NULL)) {   /* success */
00777          /* We return non-zero, but tell the PBX not to hang the channel when
00778             the thread dies -- We have to be careful now though.  We are responsible for 
00779             hanging up the channel, else it will never be hung up! */
00780          return 0;
00781       } else {
00782          ast_log(LOG_WARNING, "Unable to park call %s\n", transferee->name);
00783       }
00784       /*! \todo XXX Maybe we should have another message here instead of invalid extension XXX */
00785    } else if (ast_exists_extension(transferee, transferer_real_context, xferto, 1, transferer->cid.cid_num)) {
00786       pbx_builtin_setvar_helper(transferer, "BLINDTRANSFER", transferee->name);
00787       pbx_builtin_setvar_helper(transferee, "BLINDTRANSFER", transferer->name);
00788       res=finishup(transferee);
00789       if (!transferer->cdr) {
00790          transferer->cdr=ast_cdr_alloc();
00791          if (transferer) {
00792             ast_cdr_init(transferer->cdr, transferer); /* initilize our channel's cdr */
00793             ast_cdr_start(transferer->cdr);
00794          }
00795       }
00796       if (transferer->cdr) {
00797          ast_cdr_setdestchan(transferer->cdr, transferee->name);
00798          ast_cdr_setapp(transferer->cdr, "BLINDTRANSFER","");
00799       }
00800       if (!transferee->pbx) {
00801          /* Doh!  Use our handy async_goto functions */
00802          if (option_verbose > 2) 
00803             ast_verbose(VERBOSE_PREFIX_3 "Transferring %s to '%s' (context %s) priority 1\n"
00804                         ,transferee->name, xferto, transferer_real_context);
00805          if (ast_async_goto(transferee, transferer_real_context, xferto, 1))
00806             ast_log(LOG_WARNING, "Async goto failed :-(\n");
00807          res = -1;
00808       } else {
00809          /* Set the channel's new extension, since it exists, using transferer context */
00810          set_c_e_p(transferee, transferer_real_context, xferto, 0);
00811       }
00812       check_goto_on_transfer(transferer);
00813       return res;
00814    } else {
00815       if (option_verbose > 2) 
00816          ast_verbose(VERBOSE_PREFIX_3 "Unable to find extension '%s' in context '%s'\n", xferto, transferer_real_context);
00817    }
00818    if (ast_stream_and_wait(transferer, xferfailsound, transferer->language, AST_DIGIT_ANY) < 0) {
00819       finishup(transferee);
00820       return -1;
00821    }
00822    ast_stopstream(transferer);
00823    res = finishup(transferee);
00824    if (res) {
00825       if (option_verbose > 1)
00826          ast_verbose(VERBOSE_PREFIX_2 "Hungup during autoservice stop on '%s'\n", transferee->name);
00827       return res;
00828    }
00829    return FEATURE_RETURN_SUCCESS;
00830 }
00831 
00832 static int check_compat(struct ast_channel *c, struct ast_channel *newchan)
00833 {
00834    if (ast_channel_make_compatible(c, newchan) < 0) {
00835       ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n",
00836          c->name, newchan->name);
00837       ast_hangup(newchan);
00838       return -1;
00839    }
00840    return 0;
00841 }
00842 
00843 static int builtin_atxfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense, void *data)
00844 {
00845    struct ast_channel *transferer;
00846    struct ast_channel *transferee;
00847    const char *transferer_real_context;
00848    char xferto[256] = "";
00849    int res;
00850    int outstate=0;
00851    struct ast_channel *newchan;
00852    struct ast_channel *xferchan;
00853    struct ast_bridge_thread_obj *tobj;
00854    struct ast_bridge_config bconfig;
00855    struct ast_frame *f;
00856    int l;
00857    struct ast_datastore *features_datastore;
00858    struct ast_dial_features *dialfeatures = NULL;
00859 
00860    if (option_debug)
00861       ast_log(LOG_DEBUG, "Executing Attended Transfer %s, %s (sense=%d) \n", chan->name, peer->name, sense);
00862    set_peers(&transferer, &transferee, peer, chan, sense);
00863         transferer_real_context = real_ctx(transferer, transferee);
00864    /* Start autoservice on chan while we talk to the originator */
00865    ast_autoservice_start(transferee);
00866    ast_indicate(transferee, AST_CONTROL_HOLD);
00867    
00868    /* Transfer */
00869    res = ast_stream_and_wait(transferer, "pbx-transfer", transferer->language, AST_DIGIT_ANY);
00870    if (res < 0) {
00871       finishup(transferee);
00872       return res;
00873    }
00874    if (res > 0) /* If they've typed a digit already, handle it */
00875       xferto[0] = (char) res;
00876 
00877    /* this is specific of atxfer */
00878    res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
00879         if (res < 0) {  /* hangup, would be 0 for invalid and 1 for valid */
00880                 finishup(transferee);
00881                 return res;
00882         }
00883    if (res == 0) {
00884       ast_log(LOG_WARNING, "Did not read data.\n");
00885       finishup(transferee);
00886       if (ast_stream_and_wait(transferer, "beeperr", transferer->language, ""))
00887          return -1;
00888       return FEATURE_RETURN_SUCCESS;
00889    }
00890 
00891    /* valid extension, res == 1 */
00892    if (!ast_exists_extension(transferer, transferer_real_context, xferto, 1, transferer->cid.cid_num)) {
00893       ast_log(LOG_WARNING, "Extension %s does not exist in context %s\n",xferto,transferer_real_context);
00894       finishup(transferee);
00895       if (ast_stream_and_wait(transferer, "beeperr", transferer->language, ""))
00896          return -1;
00897       return FEATURE_RETURN_SUCCESS;
00898    }
00899 
00900    l = strlen(xferto);
00901    snprintf(xferto + l, sizeof(xferto) - l, "@%s", transferer_real_context);  /* append context */
00902    newchan = ast_feature_request_and_dial(transferer, "Local", ast_best_codec(transferer->nativeformats),
00903       xferto, atxfernoanswertimeout, &outstate, transferer->cid.cid_num, transferer->cid.cid_name, transferer->language);
00904 
00905    /* If we are the callee and we are being transferred, after the masquerade
00906    * caller features will really be the original callee features */
00907    ast_channel_lock(transferee);
00908    if ((features_datastore = ast_channel_datastore_find(transferee, &dial_features_info, NULL))) {
00909       dialfeatures = features_datastore->data;
00910    }
00911    ast_channel_unlock(transferee);
00912 
00913    if (dialfeatures && !dialfeatures->is_caller) {
00914       ast_copy_flags(&(config->features_caller), &(dialfeatures->features_callee), AST_FLAGS_ALL);
00915    }
00916 
00917    ast_indicate(transferer, -1);
00918    if (!newchan) {
00919       finishup(transferee);
00920       /* any reason besides user requested cancel and busy triggers the failed sound */
00921       if (outstate != AST_CONTROL_UNHOLD && outstate != AST_CONTROL_BUSY &&
00922             ast_stream_and_wait(transferer, xferfailsound, transferer->language, ""))
00923          return -1;
00924       return FEATURE_RETURN_SUCCESS;
00925    }
00926 
00927    if (check_compat(transferer, newchan)) {
00928       /* we do mean transferee here, NOT transferer */
00929       finishup(transferee);
00930       return -1;
00931    }
00932    memset(&bconfig,0,sizeof(struct ast_bridge_config));
00933    ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
00934    ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
00935    res = ast_bridge_call(transferer, newchan, &bconfig);
00936    if (newchan->_softhangup || !transferer->_softhangup) {
00937       ast_hangup(newchan);
00938       if (ast_stream_and_wait(transferer, xfersound, transferer->language, ""))
00939          ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
00940       finishup(transferee);
00941       transferer->_softhangup = 0;
00942       return FEATURE_RETURN_SUCCESS;
00943    }
00944    
00945    if (check_compat(transferee, newchan)) {
00946       finishup(transferee);
00947       return -1;
00948    }
00949 
00950    ast_indicate(transferee, AST_CONTROL_UNHOLD);
00951    
00952    if ((ast_autoservice_stop(transferee) < 0)
00953       || (ast_waitfordigit(transferee, 100) < 0)
00954       || (ast_waitfordigit(newchan, 100) < 0) 
00955       || ast_check_hangup(transferee) 
00956       || ast_check_hangup(newchan)) {
00957       ast_hangup(newchan);
00958       return -1;
00959    }
00960 
00961    xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, "Transfered/%s", transferee->name);
00962    if (!xferchan) {
00963       ast_hangup(newchan);
00964       return -1;
00965    }
00966    /* Make formats okay */
00967    xferchan->visible_indication = transferer->visible_indication;
00968    xferchan->readformat = transferee->readformat;
00969    xferchan->writeformat = transferee->writeformat;
00970    ast_channel_masquerade(xferchan, transferee);
00971    ast_explicit_goto(xferchan, transferee->context, transferee->exten, transferee->priority);
00972    xferchan->_state = AST_STATE_UP;
00973    ast_clear_flag(xferchan, AST_FLAGS_ALL);  
00974    xferchan->_softhangup = 0;
00975 
00976    if ((f = ast_read(xferchan)))
00977       ast_frfree(f);
00978 
00979    newchan->_state = AST_STATE_UP;
00980    ast_clear_flag(newchan, AST_FLAGS_ALL);   
00981    newchan->_softhangup = 0;
00982 
00983    tobj = ast_calloc(1, sizeof(struct ast_bridge_thread_obj));
00984    if (!tobj) {
00985       ast_hangup(xferchan);
00986       ast_hangup(newchan);
00987       return -1;
00988    }
00989     
00990    /* For the case where the transfer target is being connected with the original
00991       caller store the target's original features, and apply to the bridge */
00992    ast_channel_lock(newchan);
00993    if ((features_datastore = ast_channel_datastore_find(newchan, &dial_features_info, NULL))) {
00994       dialfeatures = features_datastore->data;
00995    }
00996    ast_channel_unlock(newchan);
00997 
00998    if (dialfeatures) {
00999       ast_copy_flags(&(config->features_callee), &(dialfeatures->features_callee), AST_FLAGS_ALL);
01000    }
01001 
01002    tobj->chan = newchan;
01003    tobj->peer = xferchan;
01004    tobj->bconfig = *config;
01005 
01006    if (tobj->bconfig.end_bridge_callback_data_fixup) {
01007       tobj->bconfig.end_bridge_callback_data_fixup(&tobj->bconfig, tobj->peer, tobj->chan);
01008    }
01009 
01010    if (ast_stream_and_wait(newchan, xfersound, newchan->language, ""))
01011       ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
01012    ast_bridge_call_thread_launch(tobj);
01013    return -1;  /* XXX meaning the channel is bridged ? */
01014 }
01015 
01016 
01017 /* add atxfer and automon as undefined so you can only use em if you configure them */
01018 #define FEATURES_COUNT (sizeof(builtin_features) / sizeof(builtin_features[0]))
01019 
01020 AST_RWLOCK_DEFINE_STATIC(features_lock);
01021 
01022 static struct ast_call_feature builtin_features[] = 
01023  {
01024    { AST_FEATURE_REDIRECT, "Blind Transfer", "blindxfer", "#", "#", builtin_blindtransfer, AST_FEATURE_FLAG_NEEDSDTMF, "" },
01025    { AST_FEATURE_REDIRECT, "Attended Transfer", "atxfer", "", "", builtin_atxfer, AST_FEATURE_FLAG_NEEDSDTMF, "" },
01026    { AST_FEATURE_AUTOMON, "One Touch Monitor", "automon", "", "", builtin_automonitor, AST_FEATURE_FLAG_NEEDSDTMF, "" },
01027    { AST_FEATURE_DISCONNECT, "Disconnect Call", "disconnect", "*", "*", builtin_disconnect, AST_FEATURE_FLAG_NEEDSDTMF, "" },
01028    { AST_FEATURE_PARKCALL, "Park Call", "parkcall", "", "", builtin_parkcall, AST_FEATURE_FLAG_NEEDSDTMF, "" },
01029 };
01030 
01031 
01032 static AST_RWLIST_HEAD_STATIC(feature_list, ast_call_feature);
01033 
01034 /*! \brief register new feature into feature_list*/
01035 void ast_register_feature(struct ast_call_feature *feature)
01036 {
01037    if (!feature) {
01038       ast_log(LOG_NOTICE,"You didn't pass a feature!\n");
01039          return;
01040    }
01041   
01042    AST_RWLIST_WRLOCK(&feature_list);
01043    AST_RWLIST_INSERT_HEAD(&feature_list, feature, feature_entry);
01044    AST_RWLIST_UNLOCK(&feature_list);
01045 
01046    if (option_verbose >= 2) {
01047       ast_verbose(VERBOSE_PREFIX_2 "Registered Feature '%s'\n",feature->sname);
01048    }
01049 }
01050 
01051 /*! \brief unregister feature from feature_list */
01052 void ast_unregister_feature(struct ast_call_feature *feature)
01053 {
01054    if (!feature)
01055       return;
01056 
01057    AST_RWLIST_WRLOCK(&feature_list);
01058    AST_RWLIST_REMOVE(&feature_list, feature, feature_entry);
01059    AST_RWLIST_UNLOCK(&feature_list);
01060    
01061    free(feature);
01062 }
01063 
01064 /*! \brief Remove all features in the list */
01065 static void ast_unregister_features(void)
01066 {
01067    struct ast_call_feature *feature;
01068 
01069    AST_RWLIST_WRLOCK(&feature_list);
01070    while ((feature = AST_LIST_REMOVE_HEAD(&feature_list, feature_entry))) {
01071       free(feature);
01072    }
01073    AST_RWLIST_UNLOCK(&feature_list);
01074 }
01075 
01076 /*! \brief find a feature by name */
01077 static struct ast_call_feature *find_dynamic_feature(const char *name)
01078 {
01079    struct ast_call_feature *tmp;
01080 
01081    AST_RWLIST_TRAVERSE(&feature_list, tmp, feature_entry) {
01082       if (!strcasecmp(tmp->sname, name)) {
01083          break;
01084       }
01085    }
01086 
01087    return tmp;
01088 }
01089 
01090 /*! \brief exec an app by feature */
01091 static int feature_exec_app(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense, void *data)
01092 {
01093    struct ast_app *app;
01094    struct ast_call_feature *feature = data;
01095    struct ast_channel *work, *idle;
01096    int res;
01097 
01098    if (!feature) { /* shouldn't ever happen! */
01099       ast_log(LOG_NOTICE, "Found feature before, but at execing we've lost it??\n");
01100       return -1; 
01101    }
01102 
01103    if (sense == FEATURE_SENSE_CHAN) {
01104       if (!ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER))
01105          return FEATURE_RETURN_KEEPTRYING;
01106       if (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF)) {
01107          work = chan;
01108          idle = peer;
01109       } else {
01110          work = peer;
01111          idle = chan;
01112       }
01113    } else {
01114       if (!ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE))
01115          return FEATURE_RETURN_KEEPTRYING;
01116       if (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF)) {
01117          work = peer;
01118          idle = chan;
01119       } else {
01120          work = chan;
01121          idle = peer;
01122       }
01123    }
01124 
01125    if (!(app = pbx_findapp(feature->app))) {
01126       ast_log(LOG_WARNING, "Could not find application (%s)\n", feature->app);
01127       return -2;
01128    }
01129 
01130    ast_autoservice_start(idle);
01131    
01132    if (!ast_strlen_zero(feature->moh_class))
01133       ast_moh_start(idle, feature->moh_class, NULL);
01134 
01135    res = pbx_exec(work, app, feature->app_args);
01136 
01137    if (!ast_strlen_zero(feature->moh_class))
01138       ast_moh_stop(idle);
01139 
01140    ast_autoservice_stop(idle);
01141 
01142    if (res == AST_PBX_KEEPALIVE) {
01143       /* do not hangup peer if feature is to be activated on it */
01144       if ((ast_test_flag(feature, AST_FEATURE_FLAG_ONPEER) && sense == FEATURE_SENSE_CHAN) || (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF) && sense == FEATURE_SENSE_PEER)) {
01145          return FEATURE_RETURN_NO_HANGUP_PEER;
01146       } else
01147          return FEATURE_RETURN_PBX_KEEPALIVE;
01148    } else if (res == AST_PBX_NO_HANGUP_PEER) {
01149       return FEATURE_RETURN_NO_HANGUP_PEER;
01150    } else if (res == AST_PBX_NO_HANGUP_PEER_PARKED) {
01151       return FEATURE_RETURN_NO_HANGUP_PEER_PARKED;
01152    } else if (res)
01153       return FEATURE_RETURN_SUCCESSBREAK;
01154    
01155    return FEATURE_RETURN_SUCCESS;   /*! \todo XXX should probably return res */
01156 }
01157 
01158 static void unmap_features(void)
01159 {
01160    int x;
01161 
01162    ast_rwlock_wrlock(&features_lock);
01163    for (x = 0; x < FEATURES_COUNT; x++)
01164       strcpy(builtin_features[x].exten, builtin_features[x].default_exten);
01165    ast_rwlock_unlock(&features_lock);
01166 }
01167 
01168 static int remap_feature(const char *name, const char *value)
01169 {
01170    int x, res = -1;
01171 
01172    ast_rwlock_wrlock(&features_lock);
01173    for (x = 0; x < FEATURES_COUNT; x++) {
01174       if (strcasecmp(builtin_features[x].sname, name))
01175          continue;
01176 
01177       ast_copy_string(builtin_features[x].exten, value, sizeof(builtin_features[x].exten));
01178       res = 0;
01179       break;
01180    }
01181    ast_rwlock_unlock(&features_lock);
01182 
01183    return res;
01184 }
01185 
01186 static int ast_feature_interpret(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense)
01187 {
01188    int x;
01189    struct ast_flags features;
01190    struct ast_call_feature *feature;
01191    const char *dynamic_features;
01192    char *tmp, *tok;
01193    int res = FEATURE_RETURN_PASSDIGITS;
01194    int feature_detected = 0;
01195 
01196    if (sense == FEATURE_SENSE_CHAN) {
01197       ast_copy_flags(&features, &(config->features_caller), AST_FLAGS_ALL);   
01198       dynamic_features = pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES");
01199    } else {
01200       ast_copy_flags(&features, &(config->features_callee), AST_FLAGS_ALL);   
01201       dynamic_features = pbx_builtin_getvar_helper(peer, "DYNAMIC_FEATURES");
01202    }
01203    if (option_debug > 2)
01204       ast_log(LOG_DEBUG, "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);
01205 
01206    ast_rwlock_rdlock(&features_lock);
01207    for (x = 0; x < FEATURES_COUNT; x++) {
01208       if ((ast_test_flag(&features, builtin_features[x].feature_mask)) &&
01209           !ast_strlen_zero(builtin_features[x].exten)) {
01210          /* Feature is up for consideration */
01211          if (!strcmp(builtin_features[x].exten, code)) {
01212             res = builtin_features[x].operation(chan, peer, config, code, sense, NULL);
01213             feature_detected = 1;
01214             break;
01215          } else if (!strncmp(builtin_features[x].exten, code, strlen(code))) {
01216             if (res == FEATURE_RETURN_PASSDIGITS)
01217                res = FEATURE_RETURN_STOREDIGITS;
01218          }
01219       }
01220    }
01221    ast_rwlock_unlock(&features_lock);
01222 
01223    if (ast_strlen_zero(dynamic_features) || feature_detected)
01224       return res;
01225 
01226    tmp = ast_strdupa(dynamic_features);
01227 
01228    while ((tok = strsep(&tmp, "#"))) {
01229       AST_RWLIST_RDLOCK(&feature_list);   
01230       if (!(feature = find_dynamic_feature(tok))) {
01231          AST_RWLIST_UNLOCK(&feature_list);
01232          continue;
01233       }
01234          
01235       /* Feature is up for consideration */
01236       if (!strcmp(feature->exten, code)) {
01237          if (option_verbose > 2)
01238             ast_verbose(VERBOSE_PREFIX_3 " Feature Found: %s exten: %s\n",feature->sname, tok);
01239          res = feature->operation(chan, peer, config, code, sense, feature);
01240          if (res != FEATURE_RETURN_KEEPTRYING) {
01241             AST_RWLIST_UNLOCK(&feature_list);
01242             break;
01243          }
01244          res = FEATURE_RETURN_PASSDIGITS;
01245       } else if (!strncmp(feature->exten, code, strlen(code)))
01246          res = FEATURE_RETURN_STOREDIGITS;
01247 
01248       AST_RWLIST_UNLOCK(&feature_list);
01249    }
01250    
01251    return res;
01252 }
01253 
01254 static void set_config_flags(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config)
01255 {
01256    int x;
01257    
01258    ast_clear_flag(config, AST_FLAGS_ALL);
01259 
01260    ast_rwlock_rdlock(&features_lock);
01261    for (x = 0; x < FEATURES_COUNT; x++) {
01262       if (!ast_test_flag(builtin_features + x, AST_FEATURE_FLAG_NEEDSDTMF))
01263          continue;
01264 
01265       if (ast_test_flag(&(config->features_caller), builtin_features[x].feature_mask))
01266          ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
01267 
01268       if (ast_test_flag(&(config->features_callee), builtin_features[x].feature_mask))
01269          ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
01270    }
01271    ast_rwlock_unlock(&features_lock);
01272    
01273    if (chan && peer && !(ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_0) && ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_1))) {
01274       const char *dynamic_features = pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES");
01275 
01276       if (dynamic_features) {
01277          char *tmp = ast_strdupa(dynamic_features);
01278          char *tok;
01279          struct ast_call_feature *feature;
01280 
01281          /* while we have a feature */
01282          while ((tok = strsep(&tmp, "#"))) {
01283             AST_RWLIST_RDLOCK(&feature_list);
01284             if ((feature = find_dynamic_feature(tok)) && ast_test_flag(feature, AST_FEATURE_FLAG_NEEDSDTMF)) {
01285                if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER))
01286                   ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
01287                if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE))
01288                   ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
01289             }
01290             AST_RWLIST_UNLOCK(&feature_list);
01291          }
01292       }
01293    }
01294 }
01295 
01296 /*! \todo XXX Check - this is very similar to the code in channel.c */
01297 static struct ast_channel *ast_feature_request_and_dial(struct ast_channel *caller, const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name, const char *language)
01298 {
01299    int state = 0;
01300    int cause = 0;
01301    int to;
01302    struct ast_channel *chan;
01303    struct ast_channel *monitor_chans[2];
01304    struct ast_channel *active_channel;
01305    int res = 0, ready = 0;
01306    
01307    if ((chan = ast_request(type, format, data, &cause))) {
01308       ast_set_callerid(chan, cid_num, cid_name, cid_num);
01309       ast_string_field_set(chan, language, language);
01310       ast_channel_inherit_variables(caller, chan); 
01311       pbx_builtin_setvar_helper(chan, "TRANSFERERNAME", caller->name);
01312          
01313       if (!ast_call(chan, data, timeout)) {
01314          struct timeval started;
01315          int x, len = 0;
01316          char *disconnect_code = NULL, *dialed_code = NULL;
01317 
01318          ast_indicate(caller, AST_CONTROL_RINGING);
01319          /* support dialing of the featuremap disconnect code while performing an attended tranfer */
01320          ast_rwlock_rdlock(&features_lock);
01321          for (x = 0; x < FEATURES_COUNT; x++) {
01322             if (strcasecmp(builtin_features[x].sname, "disconnect"))
01323                continue;
01324 
01325             disconnect_code = builtin_features[x].exten;
01326             len = strlen(disconnect_code) + 1;
01327             dialed_code = alloca(len);
01328             memset(dialed_code, 0, len);
01329             break;
01330          }
01331          ast_rwlock_unlock(&features_lock);
01332          x = 0;
01333          started = ast_tvnow();
01334          to = timeout;
01335          while (!ast_check_hangup(caller) && timeout && (chan->_state != AST_STATE_UP)) {
01336             struct ast_frame *f = NULL;
01337 
01338             monitor_chans[0] = caller;
01339             monitor_chans[1] = chan;
01340             active_channel = ast_waitfor_n(monitor_chans, 2, &to);
01341 
01342             /* see if the timeout has been violated */
01343             if(ast_tvdiff_ms(ast_tvnow(), started) > timeout) {
01344                state = AST_CONTROL_UNHOLD;
01345                ast_log(LOG_NOTICE, "We exceeded our AT-timeout\n");
01346                break; /*doh! timeout*/
01347             }
01348 
01349             if (!active_channel)
01350                continue;
01351 
01352             if (chan && (chan == active_channel)){
01353                f = ast_read(chan);
01354                if (f == NULL) { /*doh! where'd he go?*/
01355                   state = AST_CONTROL_HANGUP;
01356                   res = 0;
01357                   break;
01358                }
01359                
01360                if (f->frametype == AST_FRAME_CONTROL || f->frametype == AST_FRAME_DTMF || f->frametype == AST_FRAME_TEXT) {
01361                   if (f->subclass == AST_CONTROL_RINGING) {
01362                      state = f->subclass;
01363                      if (option_verbose > 2)
01364                         ast_verbose(VERBOSE_PREFIX_3 "%s is ringing\n", chan->name);
01365                      ast_indicate(caller, AST_CONTROL_RINGING);
01366                   } else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
01367                      state = f->subclass;
01368                      if (option_verbose > 2)
01369                         ast_verbose(VERBOSE_PREFIX_3 "%s is busy\n", chan->name);
01370                      ast_indicate(caller, AST_CONTROL_BUSY);
01371                      ast_frfree(f);
01372                      f = NULL;
01373                      break;
01374                   } else if (f->subclass == AST_CONTROL_ANSWER) {
01375                      /* This is what we are hoping for */
01376                      state = f->subclass;
01377                      ast_frfree(f);
01378                      f = NULL;
01379                      ready=1;
01380                      break;
01381                   } else if (f->subclass != -1) {
01382                      ast_log(LOG_NOTICE, "Don't know what to do about control frame: %d\n", f->subclass);
01383                   }
01384                   /* else who cares */
01385                }
01386 
01387             } else if (caller && (active_channel == caller)) {
01388                f = ast_read(caller);
01389                if (f == NULL) { /*doh! where'd he go?*/
01390                   if (caller->_softhangup && !chan->_softhangup) {
01391                      /* make this a blind transfer */
01392                      ready = 1;
01393                      break;
01394                   }
01395                   state = AST_CONTROL_HANGUP;
01396                   res = 0;
01397                   break;
01398                }
01399                
01400                if (f->frametype == AST_FRAME_DTMF) {
01401                   dialed_code[x++] = f->subclass;
01402                   dialed_code[x] = '\0';
01403                   if (strlen(dialed_code) == len) {
01404                      x = 0;
01405                   } else if (x && strncmp(dialed_code, disconnect_code, x)) {
01406                      x = 0;
01407                      dialed_code[x] = '\0';
01408                   }
01409                   if (*dialed_code && !strcmp(dialed_code, disconnect_code)) {
01410                      /* Caller Canceled the call */
01411                      state = AST_CONTROL_UNHOLD;
01412                      ast_frfree(f);
01413                      f = NULL;
01414                      break;
01415                   }
01416                }
01417             }
01418             if (f)
01419                ast_frfree(f);
01420          } /* end while */
01421       } else
01422          ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
01423    } else {
01424       ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
01425       switch(cause) {
01426       case AST_CAUSE_BUSY:
01427          state = AST_CONTROL_BUSY;
01428          break;
01429       case AST_CAUSE_CONGESTION:
01430          state = AST_CONTROL_CONGESTION;
01431          break;
01432       }
01433    }
01434    
01435    ast_indicate(caller, -1);
01436    if (chan && ready) {
01437       if (chan->_state == AST_STATE_UP) 
01438          state = AST_CONTROL_ANSWER;
01439       res = 0;
01440    } else if(chan) {
01441       res = -1;
01442       ast_hangup(chan);
01443       chan = NULL;
01444    } else {
01445       res = -1;
01446    }
01447    
01448    if (outstate)
01449       *outstate = state;
01450 
01451    return chan;
01452 }
01453 
01454 static struct ast_cdr *pick_unlocked_cdr(struct ast_cdr *cdr)
01455 {
01456    struct ast_cdr *cdr_orig = cdr;
01457    while (cdr) {
01458       if (!ast_test_flag(cdr,AST_CDR_FLAG_LOCKED))
01459          return cdr;
01460       cdr = cdr->next;
01461    }
01462    return cdr_orig; /* everybody LOCKED or some other weirdness, like a NULL */
01463 }
01464 
01465 
01466 int ast_bridge_call(struct ast_channel *chan,struct ast_channel *peer,struct ast_bridge_config *config)
01467 {
01468    /* Copy voice back and forth between the two channels.  Give the peer
01469       the ability to transfer calls with '#<extension' syntax. */
01470    struct ast_frame *f;
01471    struct ast_channel *who;
01472    char chan_featurecode[FEATURE_MAX_LEN + 1]="";
01473    char peer_featurecode[FEATURE_MAX_LEN + 1]="";
01474    char orig_channame[AST_MAX_EXTENSION];
01475    char orig_peername[AST_MAX_EXTENSION];
01476 
01477    int res;
01478    int diff;
01479    int hasfeatures=0;
01480    int hadfeatures=0;
01481    int autoloopflag;
01482    struct ast_option_header *aoh;
01483    struct ast_bridge_config backup_config;
01484    struct ast_cdr *bridge_cdr = NULL;
01485    struct ast_cdr *orig_peer_cdr = NULL;
01486    struct ast_cdr *chan_cdr = pick_unlocked_cdr(chan->cdr); /* the proper chan cdr, if there are forked cdrs */
01487    struct ast_cdr *peer_cdr = pick_unlocked_cdr(peer->cdr); /* the proper chan cdr, if there are forked cdrs */
01488    struct ast_cdr *new_chan_cdr = NULL; /* the proper chan cdr, if there are forked cdrs */
01489    struct ast_cdr *new_peer_cdr = NULL; /* the proper chan cdr, if there are forked cdrs */
01490 
01491    memset(&backup_config, 0, sizeof(backup_config));
01492 
01493    config->start_time = ast_tvnow();
01494 
01495    if (chan && peer) {
01496       pbx_builtin_setvar_helper(chan, "BRIDGEPEER", peer->name);
01497       pbx_builtin_setvar_helper(peer, "BRIDGEPEER", chan->name);
01498    } else if (chan) {
01499       pbx_builtin_setvar_helper(chan, "BLINDTRANSFER", NULL);
01500    }
01501 
01502    /* This is an interesting case.  One example is if a ringing channel gets redirected to
01503     * an extension that picks up a parked call.  This will make sure that the call taken
01504     * out of parking gets told that the channel it just got bridged to is still ringing. */
01505    if (chan->_state == AST_STATE_RINGING && peer->visible_indication != AST_CONTROL_RINGING) {
01506       ast_indicate(peer, AST_CONTROL_RINGING);
01507    }
01508 
01509    if (monitor_ok) {
01510       const char *monitor_exec;
01511       struct ast_channel *src = NULL;
01512       if (!monitor_app) { 
01513          if (!(monitor_app = pbx_findapp("Monitor")))
01514             monitor_ok=0;
01515       }
01516       if ((monitor_exec = pbx_builtin_getvar_helper(chan, "AUTO_MONITOR"))) 
01517          src = chan;
01518       else if ((monitor_exec = pbx_builtin_getvar_helper(peer, "AUTO_MONITOR")))
01519          src = peer;
01520       if (monitor_app && src) {
01521          char *tmp = ast_strdupa(monitor_exec);
01522          pbx_exec(src, monitor_app, tmp);
01523       }
01524    }
01525    
01526    set_config_flags(chan, peer, config);
01527    config->firstpass = 1;
01528 
01529    /* Answer if need be */
01530    if (ast_answer(chan))
01531       return -1;
01532 
01533    ast_copy_string(orig_channame,chan->name,sizeof(orig_channame));
01534    ast_copy_string(orig_peername,peer->name,sizeof(orig_peername));
01535    orig_peer_cdr = peer_cdr;
01536    
01537    if (!chan_cdr || (chan_cdr && !ast_test_flag(chan_cdr, AST_CDR_FLAG_POST_DISABLED))) {
01538          
01539       if (chan_cdr) {
01540          ast_set_flag(chan_cdr, AST_CDR_FLAG_MAIN);
01541          ast_cdr_update(chan);
01542          bridge_cdr = ast_cdr_dup(chan_cdr);
01543          ast_copy_string(bridge_cdr->lastapp, chan->appl, sizeof(bridge_cdr->lastapp));
01544          ast_copy_string(bridge_cdr->lastdata, chan->data, sizeof(bridge_cdr->lastdata));
01545       } else {
01546          /* better yet, in a xfer situation, find out why the chan cdr got zapped (pun unintentional) */
01547          bridge_cdr = ast_cdr_alloc(); /* this should be really, really rare/impossible? */
01548          ast_copy_string(bridge_cdr->channel, chan->name, sizeof(bridge_cdr->channel));
01549          ast_copy_string(bridge_cdr->dstchannel, peer->name, sizeof(bridge_cdr->dstchannel));
01550          ast_copy_string(bridge_cdr->uniqueid, chan->uniqueid, sizeof(bridge_cdr->uniqueid));
01551          ast_copy_string(bridge_cdr->lastapp, chan->appl, sizeof(bridge_cdr->lastapp));
01552          ast_copy_string(bridge_cdr->lastdata, chan->data, sizeof(bridge_cdr->lastdata));
01553          ast_cdr_setcid(bridge_cdr, chan);
01554          bridge_cdr->disposition = (chan->_state == AST_STATE_UP) ?  AST_CDR_ANSWERED : AST_CDR_NULL;
01555          bridge_cdr->amaflags = chan->amaflags ? chan->amaflags :  ast_default_amaflags;
01556          ast_copy_string(bridge_cdr->accountcode, chan->accountcode, sizeof(bridge_cdr->accountcode));
01557          /* Destination information */
01558          ast_copy_string(bridge_cdr->dst, chan->exten, sizeof(bridge_cdr->dst));
01559          ast_copy_string(bridge_cdr->dcontext, chan->context, sizeof(bridge_cdr->dcontext));
01560          if (peer_cdr) {
01561             bridge_cdr->start = peer_cdr->start;
01562             ast_copy_string(bridge_cdr->userfield, peer_cdr->userfield, sizeof(bridge_cdr->userfield));
01563          } else {
01564             ast_cdr_start(bridge_cdr);
01565          }
01566       }
01567       /* peer_cdr->answer will be set when a macro runs on the peer;
01568          in that case, the bridge answer will be delayed while the
01569          macro plays on the peer channel. The peer answered the call
01570          before the macro started playing. To the phone system,
01571          this is billable time for the call, even tho the caller
01572          hears nothing but ringing while the macro does its thing. */
01573       if (peer_cdr && !ast_tvzero(peer_cdr->answer)) {
01574          bridge_cdr->answer = peer_cdr->answer;
01575          chan_cdr->answer = peer_cdr->answer;
01576          bridge_cdr->disposition = peer_cdr->disposition;
01577          chan_cdr->disposition = peer_cdr->disposition;
01578       } else {
01579          ast_cdr_answer(bridge_cdr);
01580          ast_cdr_answer(chan_cdr); /* for the sake of cli status checks */
01581       }
01582       ast_set_flag(chan_cdr, AST_CDR_FLAG_BRIDGED);
01583       if (peer_cdr) {
01584          ast_set_flag(peer_cdr, AST_CDR_FLAG_BRIDGED);
01585       }
01586    }
01587    
01588    for (;;) {
01589       struct ast_channel *other; /* used later */
01590       
01591       res = ast_channel_bridge(chan, peer, config, &f, &who);
01592       
01593       if (config->feature_timer) {
01594          /* Update time limit for next pass */
01595          diff = ast_tvdiff_ms(ast_tvnow(), config->start_time);
01596          config->feature_timer -= diff;
01597          if (hasfeatures) {
01598             /* Running on backup config, meaning a feature might be being
01599                activated, but that's no excuse to keep things going 
01600                indefinitely! */
01601             if (backup_config.feature_timer && ((backup_config.feature_timer -= diff) <= 0)) {
01602                if (option_debug)
01603                   ast_log(LOG_DEBUG, "Timed out, realtime this time!\n");
01604                config->feature_timer = 0;
01605                who = chan;
01606                if (f)
01607                   ast_frfree(f);
01608                f = NULL;
01609                res = 0;
01610             } else if (config->feature_timer <= 0) {
01611                /* Not *really* out of time, just out of time for
01612                   digits to come in for features. */
01613                if (option_debug)
01614                   ast_log(LOG_DEBUG, "Timed out for feature!\n");
01615                if (!ast_strlen_zero(peer_featurecode)) {
01616                   ast_dtmf_stream(chan, peer, peer_featurecode, 0);
01617                   memset(peer_featurecode, 0, sizeof(peer_featurecode));
01618                }
01619                if (!ast_strlen_zero(chan_featurecode)) {
01620                   ast_dtmf_stream(peer, chan, chan_featurecode, 0);
01621                   memset(chan_featurecode, 0, sizeof(chan_featurecode));
01622                }
01623                if (f)
01624                   ast_frfree(f);
01625                hasfeatures = !ast_strlen_zero(chan_featurecode) || !ast_strlen_zero(peer_featurecode);
01626                if (!hasfeatures) {
01627                   /* Restore original (possibly time modified) bridge config */
01628                   memcpy(config, &backup_config, sizeof(struct ast_bridge_config));
01629                   memset(&backup_config, 0, sizeof(backup_config));
01630                }
01631                hadfeatures = hasfeatures;
01632                /* Continue as we were */
01633                continue;
01634             } else if (!f) {
01635                /* The bridge returned without a frame and there is a feature in progress.
01636                 * However, we don't think the feature has quite yet timed out, so just
01637                 * go back into the bridge. */
01638                continue;
01639             }
01640          } else {
01641             if (config->feature_timer <=0) {
01642                /* We ran out of time */
01643                config->feature_timer = 0;
01644                who = chan;
01645                if (f)
01646                   ast_frfree(f);
01647                f = NULL;
01648                res = 0;
01649             }
01650          }
01651       }
01652       if (res < 0) {
01653          if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_test_flag(peer, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan) && !ast_check_hangup(peer))
01654             ast_log(LOG_WARNING, "Bridge failed on channels %s and %s\n", chan->name, peer->name);
01655          goto before_you_go;
01656       }
01657       
01658       if (!f || (f->frametype == AST_FRAME_CONTROL &&
01659             (f->subclass == AST_CONTROL_HANGUP || f->subclass == AST_CONTROL_BUSY || 
01660                f->subclass == AST_CONTROL_CONGESTION))) {
01661          res = -1;
01662          break;
01663       }
01664       /* many things should be sent to the 'other' channel */
01665       other = (who == chan) ? peer : chan;
01666       if (f->frametype == AST_FRAME_CONTROL) {
01667          switch (f->subclass) {
01668          case AST_CONTROL_RINGING:
01669          case AST_CONTROL_FLASH:
01670          case -1:
01671             ast_indicate(other, f->subclass);
01672             break;
01673          case AST_CONTROL_HOLD:
01674          case AST_CONTROL_UNHOLD:
01675             ast_indicate_data(other, f->subclass, f->data, f->datalen);
01676             break;
01677          case AST_CONTROL_OPTION:
01678             aoh = f->data;
01679             /* Forward option Requests */
01680             if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
01681                ast_channel_setoption(other, ntohs(aoh->option), aoh->data, 
01682                   f->datalen - sizeof(struct ast_option_header), 0);
01683             }
01684             break;
01685          }
01686       } else if (f->frametype == AST_FRAME_DTMF_BEGIN) {
01687          /* eat it */
01688       } else if (f->frametype == AST_FRAME_DTMF) {
01689          char *featurecode;
01690          int sense;
01691 
01692          hadfeatures = hasfeatures;
01693          /* This cannot overrun because the longest feature is one shorter than our buffer */
01694          if (who == chan) {
01695             sense = FEATURE_SENSE_CHAN;
01696             featurecode = chan_featurecode;
01697          } else  {
01698             sense = FEATURE_SENSE_PEER;
01699             featurecode = peer_featurecode;
01700          }
01701          /*! append the event to featurecode. we rely on the string being zero-filled, and
01702           * not overflowing it. 
01703           * \todo XXX how do we guarantee the latter ?
01704           */
01705          featurecode[strlen(featurecode)] = f->subclass;
01706          /* Get rid of the frame before we start doing "stuff" with the channels */
01707          ast_frfree(f);
01708          f = NULL;
01709          config->feature_timer = backup_config.feature_timer;
01710          res = ast_feature_interpret(chan, peer, config, featurecode, sense);
01711          switch(res) {
01712          case FEATURE_RETURN_PASSDIGITS:
01713             ast_dtmf_stream(other, who, featurecode, 0);
01714             /* Fall through */
01715          case FEATURE_RETURN_SUCCESS:
01716             memset(featurecode, 0, sizeof(chan_featurecode));
01717             break;
01718          }
01719          if (res >= FEATURE_RETURN_PASSDIGITS) {
01720             res = 0;
01721          } else 
01722             break;
01723          hasfeatures = !ast_strlen_zero(chan_featurecode) || !ast_strlen_zero(peer_featurecode);
01724          if (hadfeatures && !hasfeatures) {
01725             /* Restore backup */
01726             memcpy(config, &backup_config, sizeof(struct ast_bridge_config));
01727             memset(&backup_config, 0, sizeof(struct ast_bridge_config));
01728          } else if (hasfeatures) {
01729             if (!hadfeatures) {
01730                /* Backup configuration */
01731                memcpy(&backup_config, config, sizeof(struct ast_bridge_config));
01732                /* Setup temporary config options */
01733                config->play_warning = 0;
01734                ast_clear_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING);
01735                ast_clear_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING);
01736                config->warning_freq = 0;
01737                config->warning_sound = NULL;
01738                config->end_sound = NULL;
01739                config->start_sound = NULL;
01740                config->firstpass = 0;
01741             }
01742             config->start_time = ast_tvnow();
01743             config->feature_timer = featuredigittimeout;
01744             if (option_debug)
01745                ast_log(LOG_DEBUG, "Set time limit to %ld\n", config->feature_timer);
01746          }
01747       }
01748       if (f)
01749          ast_frfree(f);
01750 
01751    }
01752   before_you_go:
01753    if (res != AST_PBX_KEEPALIVE && config->end_bridge_callback) {
01754       config->end_bridge_callback(config->end_bridge_callback_data);
01755    }
01756 
01757    autoloopflag = ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP);
01758    ast_set_flag(chan, AST_FLAG_IN_AUTOLOOP);
01759    if (res != AST_PBX_KEEPALIVE && !ast_test_flag(&(config->features_caller),AST_FEATURE_NO_H_EXTEN) && ast_exists_extension(chan, chan->context, "h", 1, chan->cid.cid_num)) {
01760       struct ast_cdr *swapper = NULL;
01761       char savelastapp[AST_MAX_EXTENSION];
01762       char savelastdata[AST_MAX_EXTENSION];
01763       char save_exten[AST_MAX_EXTENSION];
01764       int  save_prio;
01765       
01766       if (bridge_cdr && ast_opt_end_cdr_before_h_exten) {
01767          ast_cdr_end(bridge_cdr);
01768       }
01769       /* swap the bridge cdr and the chan cdr for a moment, and let the endbridge
01770          dialplan code operate on it */
01771       ast_channel_lock(chan);
01772       if (bridge_cdr) {
01773          swapper = chan->cdr;
01774          ast_copy_string(savelastapp, bridge_cdr->lastapp, sizeof(bridge_cdr->lastapp));
01775          ast_copy_string(savelastdata, bridge_cdr->lastdata, sizeof(bridge_cdr->lastdata));
01776          chan->cdr = bridge_cdr;
01777       }
01778       ast_copy_string(save_exten, chan->exten, sizeof(save_exten));
01779       ast_copy_string(chan->exten, "h", sizeof(chan->exten));
01780       save_prio = chan->priority;
01781       chan->priority = 1;
01782       ast_channel_unlock(chan);
01783       while(ast_exists_extension(chan, chan->context, chan->exten, chan->priority, chan->cid.cid_num)) {
01784          if (ast_spawn_extension(chan, chan->context, chan->exten, chan->priority, chan->cid.cid_num)) {
01785             /* Something bad happened, or a hangup has been requested. */
01786             if (option_debug)
01787                ast_log(LOG_DEBUG, "Spawn h extension (%s,%s,%d) exited non-zero on '%s'\n", chan->context, chan->exten, chan->priority, chan->name);
01788             if (option_verbose > 1)
01789                ast_verbose( VERBOSE_PREFIX_2 "Spawn h extension (%s, %s, %d) exited non-zero on '%s'\n", chan->context, chan->exten, chan->priority, chan->name);
01790             break;
01791          }
01792          chan->priority++;
01793       }
01794       /* swap it back */
01795       ast_channel_lock(chan);
01796       ast_copy_string(chan->exten, save_exten, sizeof(chan->exten));
01797       chan->priority = save_prio;
01798       if (bridge_cdr)
01799          chan->cdr = swapper;
01800       ast_set_flag(chan, AST_FLAG_BRIDGE_HANGUP_RUN);
01801       ast_channel_unlock(chan);
01802       /* protect the lastapp/lastdata against the effects of the hangup/dialplan code */
01803       if (bridge_cdr) {
01804          ast_copy_string(bridge_cdr->lastapp, savelastapp, sizeof(bridge_cdr->lastapp));
01805          ast_copy_string(bridge_cdr->lastdata, savelastdata, sizeof(bridge_cdr->lastdata));
01806       }
01807    }
01808    ast_set2_flag(chan, autoloopflag, AST_FLAG_IN_AUTOLOOP);
01809 
01810    /* obey the NoCDR() wishes. -- move the DISABLED flag to the bridge CDR if it was set on the channel during the bridge... */
01811    if (res != AST_PBX_KEEPALIVE) {
01812       new_chan_cdr = pick_unlocked_cdr(chan->cdr); /* the proper chan cdr, if there are forked cdrs */
01813       if (bridge_cdr && new_chan_cdr && ast_test_flag(new_chan_cdr, AST_CDR_FLAG_POST_DISABLED))
01814          ast_set_flag(bridge_cdr, AST_CDR_FLAG_POST_DISABLED);
01815    }
01816 
01817    /* we can post the bridge CDR at this point */
01818    if (bridge_cdr) {
01819       ast_cdr_end(bridge_cdr);
01820       ast_cdr_detach(bridge_cdr);
01821    }
01822    
01823    /* do a specialized reset on the beginning channel
01824       CDR's, if they still exist, so as not to mess up
01825       issues in future bridges;
01826       
01827       Here are the rules of the game:
01828       1. The chan and peer channel pointers will not change
01829          during the life of the bridge.
01830       2. But, in transfers, the channel names will change.
01831          between the time the bridge is started, and the
01832          time the channel ends. 
01833          Usually, when a channel changes names, it will
01834          also change CDR pointers.
01835       3. Usually, only one of the two channels (chan or peer)
01836          will change names.
01837       4. Usually, if a channel changes names during a bridge,
01838          it is because of a transfer. Usually, in these situations,
01839          it is normal to see 2 bridges running simultaneously, and
01840          it is not unusual to see the two channels that change
01841          swapped between bridges.
01842       5. After a bridge occurs, we have 2 or 3 channels' CDRs
01843          to attend to; if the chan or peer changed names,
01844          we have the before and after attached CDR's.
01845       6. Parking has to be accounted for in the code:
01846          a. Parking will cause ast_bridge_call to return
01847             either AST_PBX_NO_HANGUP_PEER or AST_PBX_NO_HANGUP_PEER_PARKED;
01848           in the latter case, peer is (most likely) a bad
01849           pointer, you can no longer deref it. If it does still
01850           exist, it is under another's thread control, and
01851           could be destroyed at any time.
01852           b. The same applies to AST_PBX_KEEPALIVE, in which
01853            case, the chan ptr cannot be used, as another thread
01854           owns it and may have destroyed the channel.
01855          c. In the former case, you need to check peer to see if it 
01856             still exists before you deref it, and obtain a lock.
01857          d. In neither case should you do an ast_hangup(peer).
01858         e. Do not overwrite the result code from ast_bridge_call.
01859    */
01860    
01861    if (res != AST_PBX_KEEPALIVE && new_chan_cdr) {
01862       struct ast_channel *chan_ptr = NULL;
01863       
01864       if (strcasecmp(orig_channame, chan->name) != 0) { 
01865          /* old channel */
01866          chan_ptr = ast_get_channel_by_name_locked(orig_channame);
01867          if (chan_ptr) {
01868             if (!ast_bridged_channel(chan_ptr)) {
01869                struct ast_cdr *cur;
01870                for (cur = chan_ptr->cdr; cur; cur = cur->next) {
01871                   if (cur == chan_cdr) {
01872                      break;
01873                   }
01874                }
01875                if (cur)
01876                   ast_cdr_specialized_reset(chan_cdr,0);
01877             }
01878             ast_channel_unlock(chan_ptr);
01879          }
01880          /* new channel */
01881          ast_cdr_specialized_reset(new_chan_cdr,0);
01882       } else {
01883          ast_cdr_specialized_reset(chan_cdr,0); /* nothing changed, reset the chan_cdr  */
01884       }
01885    }
01886 
01887    if (res != AST_PBX_NO_HANGUP_PEER_PARKED) { /* if the peer was involved in a park, don't even touch it; it's probably gone */
01888       struct ast_channel *chan_ptr = NULL;
01889       new_peer_cdr = pick_unlocked_cdr(peer->cdr); /* the proper chan cdr, if there are forked cdrs */
01890       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))
01891          ast_set_flag(new_peer_cdr, AST_CDR_FLAG_POST_DISABLED); /* DISABLED is viral-- it will propagate across a bridge */
01892       if (strcasecmp(orig_peername, peer->name) != 0) { 
01893          /* old channel */
01894          chan_ptr = ast_get_channel_by_name_locked(orig_peername);
01895          if (chan_ptr) {
01896             if (!ast_bridged_channel(chan_ptr)) {
01897                struct ast_cdr *cur;
01898                for (cur = chan_ptr->cdr; cur; cur = cur->next) {
01899                   if (cur == peer_cdr) {
01900                      break;
01901                   }
01902                }
01903                if (cur)
01904                   ast_cdr_specialized_reset(peer_cdr,0);
01905             }
01906             ast_channel_unlock(chan_ptr);
01907          }
01908          /* new channel */
01909          ast_cdr_specialized_reset(new_peer_cdr,0);
01910       } else {
01911          ast_cdr_specialized_reset(peer_cdr,0); /* nothing changed, reset the peer_cdr  */
01912       }
01913    }
01914    return res;
01915 }
01916    
01917 static void post_manager_event(const char *s, char *parkingexten, struct ast_channel *chan)
01918 {
01919    manager_event(EVENT_FLAG_CALL, s,
01920       "Exten: %s\r\n"
01921       "Channel: %s\r\n"
01922       "CallerID: %s\r\n"
01923       "CallerIDName: %s\r\n\r\n",
01924       parkingexten, 
01925       chan->name,
01926       S_OR(chan->cid.cid_num, "<unknown>"),
01927       S_OR(chan->cid.cid_name, "<unknown>")
01928       );
01929 }
01930 
01931 /*! \brief Take care of parked calls and unpark them if needed */
01932 static void *do_parking_thread(void *ignore)
01933 {
01934    fd_set rfds, efds;   /* results from previous select, to be preserved across loops. */
01935    FD_ZERO(&rfds);
01936    FD_ZERO(&efds);
01937 
01938    for (;;) {
01939       struct parkeduser *pu, *pl, *pt = NULL;
01940       int ms = -1;   /* select timeout, uninitialized */
01941       int max = -1;  /* max fd, none there yet */
01942       fd_set nrfds, nefds; /* args for the next select */
01943       FD_ZERO(&nrfds);
01944       FD_ZERO(&nefds);
01945 
01946       ast_mutex_lock(&parking_lock);
01947       pl = NULL;
01948       pu = parkinglot;
01949       /* navigate the list with prev-cur pointers to support removals */
01950       while (pu) {
01951          struct ast_channel *chan = pu->chan;   /* shorthand */
01952          int tms;        /* timeout for this item */
01953          int x;          /* fd index in channel */
01954          struct ast_context *con;
01955 
01956          if (pu->notquiteyet) { /* Pretend this one isn't here yet */
01957             pl = pu;
01958             pu = pu->next;
01959             continue;
01960          }
01961          tms = ast_tvdiff_ms(ast_tvnow(), pu->start);
01962          if (tms > pu->parkingtime) {
01963             ast_indicate(chan, AST_CONTROL_UNHOLD);
01964             /* Get chan, exten from derived kludge */
01965             if (pu->peername[0]) {
01966                char *peername = ast_strdupa(pu->peername);
01967                char *cp = strrchr(peername, '-');
01968                if (cp) 
01969                   *cp = 0;
01970                con = ast_context_find(parking_con_dial);
01971                if (!con) {
01972                   con = ast_context_create(NULL, parking_con_dial, registrar);
01973                   if (!con)
01974                      ast_log(LOG_ERROR, "Parking dial context '%s' does not exist and unable to create\n", parking_con_dial);
01975                }
01976                if (con) {
01977                   char returnexten[AST_MAX_EXTENSION];
01978                   struct ast_datastore *features_datastore;
01979                   struct ast_dial_features *dialfeatures = NULL;
01980 
01981                   ast_channel_lock(chan);
01982 
01983                   if ((features_datastore = ast_channel_datastore_find(chan, &dial_features_info, NULL)))
01984                      dialfeatures = features_datastore->data;
01985 
01986                   ast_channel_unlock(chan);
01987 
01988                   if (dialfeatures)
01989                      snprintf(returnexten, sizeof(returnexten), "%s|30|%s", peername, dialfeatures->options);
01990                   else /* Existing default */
01991                      snprintf(returnexten, sizeof(returnexten), "%s|30|t", peername);
01992 
01993                   ast_add_extension2(con, 1, peername, 1, NULL, NULL, "Dial", strdup(returnexten), ast_free, registrar);
01994                }
01995                set_c_e_p(chan, parking_con_dial, peername, 1);
01996             } else {
01997                /* They've been waiting too long, send them back to where they came.  Theoretically they
01998                   should have their original extensions and such, but we copy to be on the safe side */
01999                set_c_e_p(chan, pu->context, pu->exten, pu->priority);
02000             }
02001 
02002             post_manager_event("ParkedCallTimeOut", pu->parkingexten, chan);
02003 
02004             if (option_verbose > 1) 
02005                ast_verbose(VERBOSE_PREFIX_2 "Timeout for %s parked on %d. Returning to %s,%s,%d\n", chan->name, pu->parkingnum, chan->context, chan->exten, chan->priority);
02006             /* Start up the PBX, or hang them up */
02007             if (ast_pbx_start(chan))  {
02008                ast_log(LOG_WARNING, "Unable to restart the PBX for user on '%s', hanging them up...\n", chan->name);
02009                ast_hangup(chan);
02010             }
02011             /* And take them out of the parking lot */
02012             if (pl) 
02013                pl->next = pu->next;
02014             else
02015                parkinglot = pu->next;
02016             pt = pu;
02017             pu = pu->next;
02018             con = ast_context_find(parking_con);
02019             if (con) {
02020                if (ast_context_remove_extension2(con, pt->parkingexten, 1, NULL))
02021                   ast_log(LOG_WARNING, "Whoa, failed to remove the extension!\n");
02022                else
02023                   notify_metermaids(pt->parkingexten, parking_con);
02024             } else
02025                ast_log(LOG_WARNING, "Whoa, no parking context?\n");
02026             free(pt);
02027          } else { /* still within parking time, process descriptors */
02028             for (x = 0; x < AST_MAX_FDS; x++) {
02029                struct ast_frame *f;
02030 
02031                if (chan->fds[x] == -1 || (!FD_ISSET(chan->fds[x], &rfds) && !FD_ISSET(chan->fds[x], &efds)))
02032                   continue;   /* nothing on this descriptor */
02033 
02034                if (FD_ISSET(chan->fds[x], &efds))
02035                   ast_set_flag(chan, AST_FLAG_EXCEPTION);
02036                else
02037                   ast_clear_flag(chan, AST_FLAG_EXCEPTION);
02038                chan->fdno = x;
02039 
02040                /* See if they need servicing */
02041                f = ast_read(chan);
02042                if (!f || (f->frametype == AST_FRAME_CONTROL && f->subclass ==  AST_CONTROL_HANGUP)) {
02043                   if (f)
02044                      ast_frfree(f);
02045                   post_manager_event("ParkedCallGiveUp", pu->parkingexten, chan);
02046 
02047                   /* There's a problem, hang them up*/
02048                   if (option_verbose > 1) 
02049                      ast_verbose(VERBOSE_PREFIX_2 "%s got tired of being parked\n", chan->name);
02050                   ast_hangup(chan);
02051                   /* And take them out of the parking lot */
02052                   if (pl) 
02053                      pl->next = pu->next;
02054                   else
02055                      parkinglot = pu->next;
02056                   pt = pu;
02057                   pu = pu->next;
02058                   con = ast_context_find(parking_con);
02059                   if (con) {
02060                      if (ast_context_remove_extension2(con, pt->parkingexten, 1, NULL))
02061                         ast_log(LOG_WARNING, "Whoa, failed to remove the extension!\n");
02062                      else {
02063                         notify_metermaids(pt->parkingexten, parking_con);
02064                      }
02065                   } else
02066                      ast_log(LOG_WARNING, "Whoa, no parking context?\n");
02067                   free(pt);
02068                   break;
02069                } else {
02070                   /*! \todo XXX Maybe we could do something with packets, like dial "0" for operator or something XXX */
02071                   ast_frfree(f);
02072                   if (pu->moh_trys < 3 && !chan->generatordata) {
02073                      if (option_debug)
02074                         ast_log(LOG_DEBUG, "MOH on parked call stopped by outside source.  Restarting.\n");
02075                      ast_indicate_data(pu->chan, AST_CONTROL_HOLD, 
02076                         S_OR(parkmohclass, NULL),
02077                         !ast_strlen_zero(parkmohclass) ? strlen(parkmohclass) + 1 : 0);
02078                      pu->moh_trys++;
02079                   }
02080                   goto std;   /*! \todo XXX Ick: jumping into an else statement??? XXX */
02081                }
02082 
02083             } /* end for */
02084             if (x >= AST_MAX_FDS) {
02085 std:              for (x=0; x<AST_MAX_FDS; x++) {  /* mark fds for next round */
02086                   if (chan->fds[x] > -1) {
02087                      FD_SET(chan->fds[x], &nrfds);
02088                      FD_SET(chan->fds[x], &nefds);
02089                      if (chan->fds[x] > max)
02090                         max = chan->fds[x];
02091                   }
02092                }
02093                /* Keep track of our shortest wait */
02094                if (tms < ms || ms < 0)
02095                   ms = tms;
02096                pl = pu;
02097                pu = pu->next;
02098             }
02099          }
02100       } /* end while */
02101       ast_mutex_unlock(&parking_lock);
02102       rfds = nrfds;
02103       efds = nefds;
02104       {
02105          struct timeval tv = ast_samp2tv(ms, 1000);
02106          /* Wait for something to happen */
02107          ast_select(max + 1, &rfds, NULL, &efds, (ms > -1) ? &tv : NULL);
02108       }
02109       pthread_testcancel();
02110    }
02111    return NULL;   /* Never reached */
02112 }
02113 
02114 /*! \brief Park a call */
02115 static int park_call_exec(struct ast_channel *chan, void *data)
02116 {
02117    /* Cache the original channel name in case we get masqueraded in the middle
02118     * of a park--it is still theoretically possible for a transfer to happen before
02119     * we get here, but it is _really_ unlikely */
02120    char *orig_chan_name = ast_strdupa(chan->name);
02121    char orig_exten[AST_MAX_EXTENSION];
02122    int orig_priority = chan->priority;
02123 
02124    /* Data is unused at the moment but could contain a parking
02125       lot context eventually */
02126    int res = 0;
02127    struct ast_module_user *u;
02128 
02129    u = ast_module_user_add(chan);
02130 
02131    ast_copy_string(orig_exten, chan->exten, sizeof(orig_exten));
02132 
02133    /* Setup the exten/priority to be s/1 since we don't know
02134       where this call should return */
02135    strcpy(chan->exten, "s");
02136    chan->priority = 1;
02137    /* Answer if call is not up */
02138    if (chan->_state != AST_STATE_UP)
02139       res = ast_answer(chan);
02140    /* Sleep to allow VoIP streams to settle down */
02141    if (!res)
02142       res = ast_safe_sleep(chan, 1000);
02143    /* Park the call */
02144    if (!res) {
02145       res = park_call_full(chan, chan, 0, NULL, orig_chan_name);
02146       /* Continue on in the dialplan */
02147       if (res == 1) {
02148          ast_copy_string(chan->exten, orig_exten, sizeof(chan->exten));
02149          chan->priority = orig_priority;
02150          res = 0;
02151       } else if (!res)
02152          res = AST_PBX_KEEPALIVE;
02153    }
02154 
02155    ast_module_user_remove(u);
02156 
02157    return res;
02158 }
02159 
02160 /*! \brief Pickup parked call */
02161 static int park_exec(struct ast_channel *chan, void *data)
02162 {
02163    int res = 0;
02164    struct ast_module_user *u;
02165    struct ast_channel *peer=NULL;
02166    struct parkeduser *pu, *pl=NULL;
02167    struct ast_context *con;
02168 
02169    int park;
02170    struct ast_bridge_config config;
02171 
02172    if (!data) {
02173       ast_log(LOG_WARNING, "Parkedcall requires an argument (extension number)\n");
02174       return -1;
02175    }
02176    
02177    u = ast_module_user_add(chan);
02178 
02179    park = atoi((char *)data);
02180    ast_mutex_lock(&parking_lock);
02181    pu = parkinglot;
02182    while(pu) {
02183       if (pu->parkingnum == park) {
02184          if (pu->chan->pbx) { /* do not allow call to be picked up until the PBX thread is finished */
02185             ast_mutex_unlock(&parking_lock);
02186             ast_module_user_remove(u);
02187             return -1;
02188          }
02189          if (pl)
02190             pl->next = pu->next;
02191          else
02192             parkinglot = pu->next;
02193          break;
02194       }
02195       pl = pu;
02196       pu = pu->next;
02197    }
02198    ast_mutex_unlock(&parking_lock);
02199    if (pu) {
02200       peer = pu->chan;
02201       con = ast_context_find(parking_con);
02202       if (con) {
02203          if (ast_context_remove_extension2(con, pu->parkingexten, 1, NULL))
02204             ast_log(LOG_WARNING, "Whoa, failed to remove the extension!\n");
02205          else
02206             notify_metermaids(pu->parkingexten, parking_con);
02207       } else
02208          ast_log(LOG_WARNING, "Whoa, no parking context?\n");
02209 
02210       manager_event(EVENT_FLAG_CALL, "UnParkedCall",
02211          "Exten: %s\r\n"
02212          "Channel: %s\r\n"
02213          "From: %s\r\n"
02214          "CallerID: %s\r\n"
02215          "CallerIDName: %s\r\n",
02216          pu->parkingexten, pu->chan->name, chan->name,
02217          S_OR(pu->chan->cid.cid_num, "<unknown>"),
02218          S_OR(pu->chan->cid.cid_name, "<unknown>")
02219          );
02220 
02221       free(pu);
02222    }
02223    /* JK02: it helps to answer the channel if not already up */
02224    if (chan->_state != AST_STATE_UP)
02225       ast_answer(chan);
02226 
02227    if (peer) {
02228       /* Play a courtesy to the source(s) configured to prefix the bridge connecting */
02229       
02230       if (!ast_strlen_zero(courtesytone)) {
02231          int error = 0;
02232          ast_indicate(peer, AST_CONTROL_UNHOLD);
02233          if (parkedplay == 0) {
02234             error = ast_stream_and_wait(chan, courtesytone, chan->language, "");
02235          } else if (parkedplay == 1) {
02236             error = ast_stream_and_wait(peer, courtesytone, chan->language, "");
02237          } else if (parkedplay == 2) {
02238             if (!ast_streamfile(chan, courtesytone, chan->language) &&
02239                   !ast_streamfile(peer, courtesytone, chan->language)) {
02240                /*! \todo XXX we would like to wait on both! */
02241                res = ast_waitstream(chan, "");
02242                if (res >= 0)
02243                   res = ast_waitstream(peer, "");
02244                if (res < 0)
02245                   error = 1;
02246             }
02247                         }
02248          if (error) {
02249             ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
02250             ast_hangup(peer);
02251             ast_module_user_remove(u);
02252             return -1;
02253          }
02254       } else
02255          ast_indicate(peer, AST_CONTROL_UNHOLD); 
02256 
02257       res = ast_channel_make_compatible(chan, peer);
02258       if (res < 0) {
02259          ast_log(LOG_WARNING, "Could not make channels %s and %s compatible for bridge\n", chan->name, peer->name);
02260          ast_hangup(peer);
02261          ast_module_user_remove(u);
02262          return -1;
02263       }
02264       /* This runs sorta backwards, since we give the incoming channel control, as if it
02265          were the person called. */
02266       if (option_verbose > 2) 
02267          ast_verbose(VERBOSE_PREFIX_3 "Channel %s connected to parked call %d\n", chan->name, park);
02268 
02269       pbx_builtin_setvar_helper(chan, "PARKEDCHANNEL", peer->name);
02270       ast_cdr_setdestchan(chan->cdr, peer->name);
02271       memset(&config, 0, sizeof(struct ast_bridge_config));
02272 
02273       if ((parkedcalltransfers == AST_FEATURE_FLAG_BYCALLEE) || (parkedcalltransfers == AST_FEATURE_FLAG_BYBOTH)) {
02274          ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
02275       }
02276       if ((parkedcalltransfers == AST_FEATURE_FLAG_BYCALLER) || (parkedcalltransfers == AST_FEATURE_FLAG_BYBOTH)) {
02277          ast_set_flag(&(config.features_caller), AST_FEATURE_REDIRECT);
02278       }
02279       res = ast_bridge_call(chan, peer, &config);
02280 
02281       pbx_builtin_setvar_helper(chan, "PARKEDCHANNEL", peer->name);
02282       ast_cdr_setdestchan(chan->cdr, peer->name);
02283 
02284       /* Simulate the PBX hanging up */
02285       if (res != AST_PBX_NO_HANGUP_PEER && res != AST_PBX_NO_HANGUP_PEER_PARKED)
02286          ast_hangup(peer);
02287       ast_module_user_remove(u);
02288       return res;
02289    } else {
02290       /*! \todo XXX Play a message XXX */
02291       if (ast_stream_and_wait(chan, "pbx-invalidpark", chan->language, ""))
02292          ast_log(LOG_WARNING, "ast_streamfile of %s failed on %s\n", "pbx-invalidpark", chan->name);
02293       if (option_verbose > 2) 
02294          ast_verbose(VERBOSE_PREFIX_3 "Channel %s tried to talk to nonexistent parked call %d\n", chan->name, park);
02295       res = -1;
02296    }
02297 
02298    ast_module_user_remove(u);
02299 
02300    return res;
02301 }
02302 
02303 static int handle_showfeatures(int fd, int argc, char *argv[])
02304 {
02305    int i;
02306    struct ast_call_feature *feature;
02307    char format[] = "%-25s %-7s %-7s\n";
02308 
02309    ast_cli(fd, format, "Builtin Feature", "Default", "Current");
02310    ast_cli(fd, format, "---------------", "-------", "-------");
02311 
02312    ast_cli(fd, format, "Pickup", "*8", ast_pickup_ext());      /* default hardcoded above, so we'll hardcode it here */
02313 
02314    ast_rwlock_rdlock(&features_lock);
02315    for (i = 0; i < FEATURES_COUNT; i++)
02316       ast_cli(fd, format, builtin_features[i].fname, builtin_features[i].default_exten, builtin_features[i].exten);
02317    ast_rwlock_unlock(&features_lock);
02318 
02319    ast_cli(fd, "\n");
02320    ast_cli(fd, format, "Dynamic Feature", "Default", "Current");
02321    ast_cli(fd, format, "---------------", "-------", "-------");
02322    if (AST_RWLIST_EMPTY(&feature_list)) {
02323       ast_cli(fd, "(none)\n");
02324    } else {
02325       AST_RWLIST_RDLOCK(&feature_list);
02326       AST_RWLIST_TRAVERSE(&feature_list, feature, feature_entry) {
02327          ast_cli(fd, format, feature->sname, "no def", feature->exten);
02328       }
02329       AST_RWLIST_UNLOCK(&feature_list);
02330    }
02331    ast_cli(fd, "\nCall parking\n");
02332    ast_cli(fd, "------------\n");
02333    ast_cli(fd,"%-20s:   %s\n", "Parking extension", parking_ext);
02334    ast_cli(fd,"%-20s:   %s\n", "Parking context", parking_con);
02335    ast_cli(fd,"%-20s:   %d-%d\n", "Parked call extensions", parking_start, parking_stop);
02336    ast_cli(fd,"\n");
02337    
02338    return RESULT_SUCCESS;
02339 }
02340 
02341 static char mandescr_bridge[] =
02342 "Description: Bridge together two channels already in the PBX\n"
02343 "Variables: ( Headers marked with * are required )\n"
02344 "   *Channel1: Channel to Bridge to Channel2\n"
02345 "   *Channel2: Channel to Bridge to Channel1\n"
02346 "        Tone: (Yes|No) Play courtesy tone to Channel 2\n"
02347 "\n";
02348 
02349 static void do_bridge_masquerade(struct ast_channel *chan, struct ast_channel *tmpchan)
02350 {
02351    ast_moh_stop(chan);
02352    ast_mutex_lock(&chan->lock);
02353    ast_setstate(tmpchan, chan->_state);
02354    tmpchan->readformat = chan->readformat;
02355    tmpchan->writeformat = chan->writeformat;
02356    ast_channel_masquerade(tmpchan, chan);
02357    ast_mutex_lock(&tmpchan->lock);
02358    ast_do_masquerade(tmpchan);
02359    /* when returning from bridge, the channel will continue at the next priority */
02360    ast_explicit_goto(tmpchan, chan->context, chan->exten, chan->priority + 1);
02361    ast_mutex_unlock(&tmpchan->lock);
02362    ast_mutex_unlock(&chan->lock);
02363 }
02364 
02365 static int action_bridge(struct mansession *s, const struct message *m)
02366 {
02367    const char *channela = astman_get_header(m, "Channel1");
02368    const char *channelb = astman_get_header(m, "Channel2");
02369    const char *playtone = astman_get_header(m, "Tone");
02370    struct ast_channel *chana = NULL, *chanb = NULL;
02371    struct ast_channel *tmpchana = NULL, *tmpchanb = NULL;
02372    struct ast_bridge_thread_obj *tobj = NULL;
02373 
02374    /* make sure valid channels were specified */
02375    if (!ast_strlen_zero(channela) && !ast_strlen_zero(channelb)) {
02376       chana = ast_get_channel_by_name_prefix_locked(channela, strlen(channela));
02377       chanb = ast_get_channel_by_name_prefix_locked(channelb, strlen(channelb));
02378       if (chana)
02379          ast_mutex_unlock(&chana->lock);
02380       if (chanb)
02381          ast_mutex_unlock(&chanb->lock);
02382 
02383       /* send errors if any of the channels could not be found/locked */
02384       if (!chana) {
02385          char buf[256];
02386          snprintf(buf, sizeof(buf), "Channel1 does not exists: %s", channela);
02387          astman_send_error(s, m, buf);
02388          return 0;
02389       }
02390       if (!chanb) {
02391          char buf[256];
02392          snprintf(buf, sizeof(buf), "Channel2 does not exists: %s", channelb);
02393          astman_send_error(s, m, buf);
02394          return 0;
02395       }
02396    } else {
02397       astman_send_error(s, m, "Missing channel parameter in request");
02398       return 0;
02399    }
02400 
02401    /* Answer the channels if needed */
02402    if (chana->_state != AST_STATE_UP)
02403       ast_answer(chana);
02404    if (chanb->_state != AST_STATE_UP)
02405       ast_answer(chanb);
02406 
02407    /* create the placeholder channels and grab the other channels */
02408    if (!(tmpchana = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL, 
02409       NULL, NULL, 0, "Bridge/%s", chana->name))) {
02410       astman_send_error(s, m, "Unable to create temporary channel!");
02411       return 1;
02412    }
02413 
02414    if (!(tmpchanb = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL, 
02415       NULL, NULL, 0, "Bridge/%s", chanb->name))) {
02416       astman_send_error(s, m, "Unable to create temporary channels!");
02417       ast_channel_free(tmpchana);
02418       return 1;
02419    }
02420 
02421    do_bridge_masquerade(chana, tmpchana);
02422    do_bridge_masquerade(chanb, tmpchanb);
02423    
02424    /* make the channels compatible, send error if we fail doing so */
02425    if (ast_channel_make_compatible(tmpchana, tmpchanb)) {
02426       ast_log(LOG_WARNING, "Could not make channels %s and %s compatible for manager bridge\n", tmpchana->name, tmpchanb->name);
02427       astman_send_error(s, m, "Could not make channels compatible for manager bridge");
02428       ast_hangup(tmpchana);
02429       ast_hangup(tmpchanb);
02430       return 1;
02431    }
02432 
02433    /* setup the bridge thread object and start the bridge */
02434    if (!(tobj = ast_calloc(1, sizeof(*tobj)))) {
02435       ast_log(LOG_WARNING, "Unable to spawn a new bridge thread on %s and %s: %s\n", tmpchana->name, tmpchanb->name, strerror(errno));
02436       astman_send_error(s, m, "Unable to spawn a new bridge thread");
02437       ast_hangup(tmpchana);
02438       ast_hangup(tmpchanb);
02439       return 1;
02440    }
02441 
02442    tobj->chan = tmpchana;
02443    tobj->peer = tmpchanb;
02444    tobj->return_to_pbx = 1;
02445    
02446    if (ast_true(playtone)) {
02447       if (!ast_strlen_zero(xfersound) && !ast_streamfile(tmpchanb, xfersound, tmpchanb->language)) {
02448          if (ast_waitstream(tmpchanb, "") < 0)
02449             ast_log(LOG_WARNING, "Failed to play a courtesy tone on chan %s\n", tmpchanb->name);
02450       }
02451    }
02452 
02453    ast_bridge_call_thread_launch(tobj);
02454 
02455    astman_send_ack(s, m, "Launched bridge thread with success");
02456 
02457    return 0;
02458 }
02459 
02460 static char showfeatures_help[] =
02461 "Usage: feature list\n"
02462 "       Lists currently configured features.\n";
02463 
02464 static int handle_parkedcalls(int fd, int argc, char *argv[])
02465 {
02466    struct parkeduser *cur;
02467    int numparked = 0;
02468 
02469    ast_cli(fd, "%4s %25s (%-15s %-12s %-4s) %-6s \n", "Num", "Channel"
02470       , "Context", "Extension", "Pri", "Timeout");
02471 
02472    ast_mutex_lock(&parking_lock);
02473 
02474    for (cur = parkinglot; cur; cur = cur->next) {
02475       ast_cli(fd, "%-10.10s %25s (%-15s %-12s %-4d) %6lds\n"
02476          ,cur->parkingexten, cur->chan->name, cur->context, cur->exten
02477          ,cur->priority, cur->start.tv_sec + (cur->parkingtime/1000) - time(NULL));
02478 
02479       numparked++;
02480    }
02481    ast_mutex_unlock(&parking_lock);
02482    ast_cli(fd, "%d parked call%s.\n", numparked, (numparked != 1) ? "s" : "");
02483 
02484 
02485    return RESULT_SUCCESS;
02486 }
02487 
02488 static char showparked_help[] =
02489 "Usage: show parkedcalls\n"
02490 "       Lists currently parked calls.\n";
02491 
02492 static struct ast_cli_entry cli_show_features_deprecated = {
02493    { "show", "features", NULL },
02494    handle_showfeatures, NULL,
02495    NULL };
02496 
02497 static struct ast_cli_entry cli_features[] = {
02498    { { "feature", "show", NULL },
02499    handle_showfeatures, "Lists configured features",
02500    showfeatures_help, NULL, &cli_show_features_deprecated },
02501 
02502    { { "show", "parkedcalls", NULL },
02503    handle_parkedcalls, "Lists parked calls",
02504    showparked_help },
02505 };
02506 
02507 /*! \brief Dump lot status */
02508 static int manager_parking_status(struct mansession *s, const struct message *m)
02509 {
02510    struct parkeduser *cur;
02511    const char *id = astman_get_header(m, "ActionID");
02512    char idText[256] = "";
02513 
02514    if (!ast_strlen_zero(id))
02515       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
02516 
02517    astman_send_ack(s, m, "Parked calls will follow");
02518 
02519    ast_mutex_lock(&parking_lock);
02520 
02521    for (cur = parkinglot; cur; cur = cur->next) {
02522       astman_append(s, "Event: ParkedCall\r\n"
02523          "Exten: %d\r\n"
02524          "Channel: %s\r\n"
02525          "From: %s\r\n"
02526          "Timeout: %ld\r\n"
02527          "CallerID: %s\r\n"
02528          "CallerIDName: %s\r\n"
02529          "%s"
02530          "\r\n",
02531          cur->parkingnum, cur->chan->name, cur->peername,
02532          (long) cur->start.tv_sec + (long) (cur->parkingtime / 1000) - (long) time(NULL),
02533          S_OR(cur->chan->cid.cid_num, ""),   /* XXX in other places it is <unknown> */
02534          S_OR(cur->chan->cid.cid_name, ""),
02535          idText);
02536    }
02537 
02538    astman_append(s,
02539       "Event: ParkedCallsComplete\r\n"
02540       "%s"
02541       "\r\n",idText);
02542 
02543    ast_mutex_unlock(&parking_lock);
02544 
02545    return RESULT_SUCCESS;
02546 }
02547 
02548 static char mandescr_park[] =
02549 "Description: Park a channel.\n"
02550 "Variables: (Names marked with * are required)\n"
02551 "  *Channel: Channel name to park\n"
02552 "  *Channel2: Channel to announce park info to (and return to if timeout)\n"
02553 "  Timeout: Number of milliseconds to wait before callback.\n";  
02554 
02555 static int manager_park(struct mansession *s, const struct message *m)
02556 {
02557    const char *channel = astman_get_header(m, "Channel");
02558    const char *channel2 = astman_get_header(m, "Channel2");
02559    const char *timeout = astman_get_header(m, "Timeout");
02560    char buf[BUFSIZ];
02561    int to = 0;
02562    int res = 0;
02563    int parkExt = 0;
02564    struct ast_channel *ch1, *ch2;
02565 
02566    if (ast_strlen_zero(channel)) {
02567       astman_send_error(s, m, "Channel not specified");
02568       return 0;
02569    }
02570 
02571    if (ast_strlen_zero(channel2)) {
02572       astman_send_error(s, m, "Channel2 not specified");
02573       return 0;
02574    }
02575 
02576    ch1 = ast_get_channel_by_name_locked(channel);
02577    if (!ch1) {
02578       snprintf(buf, sizeof(buf), "Channel does not exist: %s", channel);
02579       astman_send_error(s, m, buf);
02580       return 0;
02581    }
02582 
02583    ch2 = ast_get_channel_by_name_locked(channel2);
02584    if (!ch2) {
02585       snprintf(buf, sizeof(buf), "Channel does not exist: %s", channel2);
02586       astman_send_error(s, m, buf);
02587       ast_channel_unlock(ch1);
02588       return 0;
02589    }
02590 
02591    if (!ast_strlen_zero(timeout)) {
02592       sscanf(timeout, "%d", &to);
02593    }
02594 
02595    res = ast_masq_park_call(ch1, ch2, to, &parkExt);
02596    if (!res) {
02597       ast_softhangup(ch2, AST_SOFTHANGUP_EXPLICIT);
02598       astman_send_ack(s, m, "Park successful");
02599    } else {
02600       astman_send_error(s, m, "Park failure");
02601    }
02602 
02603    ast_channel_unlock(ch1);
02604    ast_channel_unlock(ch2);
02605 
02606    return 0;
02607 }
02608 
02609 
02610 int ast_pickup_call(struct ast_channel *chan)
02611 {
02612    struct ast_channel *cur = NULL;
02613    int res = -1;
02614 
02615    while ((cur = ast_channel_walk_locked(cur)) != NULL) {
02616       if (!cur->pbx && 
02617          (cur != chan) &&
02618          (chan->pickupgroup & cur->callgroup) &&
02619          ((cur->_state == AST_STATE_RINGING) ||
02620           (cur->_state == AST_STATE_RING))) {
02621             break;
02622       }
02623       ast_channel_unlock(cur);
02624    }
02625    if (cur) {
02626       if (option_debug)
02627          ast_log(LOG_DEBUG, "Call pickup on chan '%s' by '%s'\n",cur->name, chan->name);
02628       res = ast_answer(chan);
02629       if (res)
02630          ast_log(LOG_WARNING, "Unable to answer '%s'\n", chan->name);
02631       res = ast_queue_control(chan, AST_CONTROL_ANSWER);
02632       if (res)
02633          ast_log(LOG_WARNING, "Unable to queue answer on '%s'\n", chan->name);
02634       res = ast_channel_masquerade(cur, chan);
02635       if (res)
02636          ast_log(LOG_WARNING, "Unable to masquerade '%s' into '%s'\n", chan->name, cur->name);     /* Done */
02637       ast_channel_unlock(cur);
02638    } else   {
02639       if (option_debug)
02640          ast_log(LOG_DEBUG, "No call pickup possible...\n");
02641    }
02642    return res;
02643 }
02644 
02645 /*! \brief Add parking hints for all defined parking lots */
02646 static void park_add_hints(char *context, int start, int stop)
02647 {
02648    int numext;
02649    char device[AST_MAX_EXTENSION];
02650    char exten[10];
02651 
02652    for (numext = start; numext <= stop; numext++) {
02653       snprintf(exten, sizeof(exten), "%d", numext);
02654       snprintf(device, sizeof(device), "park:%s@%s", exten, context);
02655       ast_add_extension(context, 1, exten, PRIORITY_HINT, NULL, NULL, device, NULL, NULL, registrar);
02656    }
02657 }
02658 
02659 
02660 static int load_config(void) 
02661 {
02662    int start = 0, end = 0;
02663    int res;
02664    struct ast_context *con = NULL;
02665    struct ast_config *cfg = NULL;
02666    struct ast_variable *var = NULL;
02667    char old_parking_ext[AST_MAX_EXTENSION];
02668    char old_parking_con[AST_MAX_EXTENSION] = "";
02669 
02670    if (!ast_strlen_zero(parking_con)) {
02671       strcpy(old_parking_ext, parking_ext);
02672       strcpy(old_parking_con, parking_con);
02673    } 
02674 
02675    /* Reset to defaults */
02676    strcpy(parking_con, "parkedcalls");
02677    strcpy(parking_con_dial, "park-dial");
02678    strcpy(parking_ext, "700");
02679    strcpy(pickup_ext, "*8");
02680    strcpy(parkmohclass, "default");
02681    courtesytone[0] = '\0';
02682    strcpy(xfersound, "beep");
02683    strcpy(xferfailsound, "pbx-invalid");
02684    parking_start = 701;
02685    parking_stop = 750;
02686    parkfindnext = 0;
02687    adsipark = 0;
02688    parkaddhints = 0;
02689    parkedcalltransfers = AST_FEATURE_FLAG_BYBOTH;
02690 
02691    transferdigittimeout = DEFAULT_TRANSFER_DIGIT_TIMEOUT;
02692    featuredigittimeout = DEFAULT_FEATURE_DIGIT_TIMEOUT;
02693    atxfernoanswertimeout = DEFAULT_NOANSWER_TIMEOUT_ATTENDED_TRANSFER;
02694 
02695    cfg = ast_config_load("features.conf");
02696    if (!cfg) {
02697       ast_log(LOG_WARNING,"Could not load features.conf\n");
02698       return AST_MODULE_LOAD_DECLINE;
02699    }
02700    for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
02701       if (!strcasecmp(var->name, "parkext")) {
02702          ast_copy_string(parking_ext, var->value, sizeof(parking_ext));
02703       } else if (!strcasecmp(var->name, "context")) {
02704          ast_copy_string(parking_con, var->value, sizeof(parking_con));
02705       } else if (!strcasecmp(var->name, "parkingtime")) {
02706          if ((sscanf(var->value, "%d", &parkingtime) != 1) || (parkingtime < 1)) {
02707             ast_log(LOG_WARNING, "%s is not a valid parkingtime\n", var->value);
02708             parkingtime = DEFAULT_PARK_TIME;
02709          } else
02710             parkingtime = parkingtime * 1000;
02711       } else if (!strcasecmp(var->name, "parkpos")) {
02712          if (sscanf(var->value, "%d-%d", &start, &end) != 2) {
02713             ast_log(LOG_WARNING, "Format for parking positions is a-b, where a and b are numbers at line %d of features.conf\n", var->lineno);
02714          } else {
02715             parking_start = start;
02716             parking_stop = end;
02717          }
02718       } else if (!strcasecmp(var->name, "findslot")) {
02719          parkfindnext = (!strcasecmp(var->value, "next"));
02720       } else if (!strcasecmp(var->name, "parkinghints")) {
02721          parkaddhints = ast_true(var->value);
02722       } else if (!strcasecmp(var->name, "parkedcalltransfers")) {
02723          if (!strcasecmp(var->value, "no"))
02724             parkedcalltransfers = 0;
02725          else if (!strcasecmp(var->value, "caller"))
02726             parkedcalltransfers = AST_FEATURE_FLAG_BYCALLER;
02727          else if (!strcasecmp(var->value, "callee"))
02728             parkedcalltransfers = AST_FEATURE_FLAG_BYCALLEE;
02729          else if (!strcasecmp(var->value, "both"))
02730             parkedcalltransfers = AST_FEATURE_FLAG_BYBOTH;
02731       } else if (!strcasecmp(var->name, "adsipark")) {
02732          adsipark = ast_true(var->value);
02733       } else if (!strcasecmp(var->name, "transferdigittimeout")) {
02734          if ((sscanf(var->value, "%d", &transferdigittimeout) != 1) || (transferdigittimeout < 1)) {
02735             ast_log(LOG_WARNING, "%s is not a valid transferdigittimeout\n", var->value);
02736             transferdigittimeout = DEFAULT_TRANSFER_DIGIT_TIMEOUT;
02737          } else
02738             transferdigittimeout = transferdigittimeout * 1000;
02739       } else if (!strcasecmp(var->name, "featuredigittimeout")) {
02740          if ((sscanf(var->value, "%d", &featuredigittimeout) != 1) || (featuredigittimeout < 1)) {
02741             ast_log(LOG_WARNING, "%s is not a valid featuredigittimeout\n", var->value);
02742             featuredigittimeout = DEFAULT_FEATURE_DIGIT_TIMEOUT;
02743          }
02744       } else if (!strcasecmp(var->name, "atxfernoanswertimeout")) {
02745          if ((sscanf(var->value, "%d", &atxfernoanswertimeout) != 1) || (atxfernoanswertimeout < 1)) {
02746             ast_log(LOG_WARNING, "%s is not a valid atxfernoanswertimeout\n", var->value);
02747             atxfernoanswertimeout = DEFAULT_NOANSWER_TIMEOUT_ATTENDED_TRANSFER;
02748          } else
02749             atxfernoanswertimeout = atxfernoanswertimeout * 1000;
02750       } else if (!strcasecmp(var->name, "courtesytone")) {
02751          ast_copy_string(courtesytone, var->value, sizeof(courtesytone));
02752       }  else if (!strcasecmp(var->name, "parkedplay")) {
02753          if (!strcasecmp(var->value, "both"))
02754             parkedplay = 2;
02755          else if (!strcasecmp(var->value, "parked"))
02756             parkedplay = 1;
02757          else
02758             parkedplay = 0;
02759       } else if (!strcasecmp(var->name, "xfersound")) {
02760          ast_copy_string(xfersound, var->value, sizeof(xfersound));
02761       } else if (!strcasecmp(var->name, "xferfailsound")) {
02762          ast_copy_string(xferfailsound, var->value, sizeof(xferfailsound));
02763       } else if (!strcasecmp(var->name, "pickupexten")) {
02764          ast_copy_string(pickup_ext, var->value, sizeof(pickup_ext));
02765       } else if (!strcasecmp(var->name, "parkedmusicclass")) {
02766          ast_copy_string(parkmohclass, var->value, sizeof(parkmohclass));
02767       }
02768    }
02769 
02770    unmap_features();
02771    for (var = ast_variable_browse(cfg, "featuremap"); var; var = var->next) {
02772       if (remap_feature(var->name, var->value))
02773          ast_log(LOG_NOTICE, "Unknown feature '%s'\n", var->name);
02774    }
02775 
02776    /* Map a key combination to an application*/
02777    ast_unregister_features();
02778    for (var = ast_variable_browse(cfg, "applicationmap"); var; var = var->next) {
02779       char *tmp_val = ast_strdupa(var->value);
02780       char *exten, *activateon, *activatedby, *app, *app_args, *moh_class; 
02781       struct ast_call_feature *feature;
02782 
02783       /* strsep() sets the argument to NULL if match not found, and it
02784        * is safe to use it with a NULL argument, so we don't check
02785        * between calls.
02786        */
02787       exten = strsep(&tmp_val,",");
02788       activatedby = strsep(&tmp_val,",");
02789       app = strsep(&tmp_val,",");
02790       app_args = strsep(&tmp_val,",");
02791       moh_class = strsep(&tmp_val,",");
02792 
02793       activateon = strsep(&activatedby, "/");   
02794 
02795       /*! \todo XXX var_name or app_args ? */
02796       if (ast_strlen_zero(app) || ast_strlen_zero(exten) || ast_strlen_zero(activateon) || ast_strlen_zero(var->name)) {
02797          ast_log(LOG_NOTICE, "Please check the feature Mapping Syntax, either extension, name, or app aren't provided %s %s %s %s\n",
02798             app, exten, activateon, var->name);
02799          continue;
02800       }
02801 
02802       AST_RWLIST_RDLOCK(&feature_list);
02803       if ((feature = find_dynamic_feature(var->name))) {
02804          AST_RWLIST_UNLOCK(&feature_list);
02805          ast_log(LOG_WARNING, "Dynamic Feature '%s' specified more than once!\n", var->name);
02806          continue;
02807       }
02808       AST_RWLIST_UNLOCK(&feature_list);
02809             
02810       if (!(feature = ast_calloc(1, sizeof(*feature))))
02811          continue;               
02812 
02813       ast_copy_string(feature->sname, var->name, FEATURE_SNAME_LEN);
02814       ast_copy_string(feature->app, app, FEATURE_APP_LEN);
02815       ast_copy_string(feature->exten, exten, FEATURE_EXTEN_LEN);
02816       
02817       if (app_args) 
02818          ast_copy_string(feature->app_args, app_args, FEATURE_APP_ARGS_LEN);
02819 
02820       if (moh_class)
02821          ast_copy_string(feature->moh_class, moh_class, FEATURE_MOH_LEN);
02822          
02823       ast_copy_string(feature->exten, exten, sizeof(feature->exten));
02824       feature->operation = feature_exec_app;
02825       ast_set_flag(feature, AST_FEATURE_FLAG_NEEDSDTMF);
02826 
02827       /* Allow caller and calle to be specified for backwards compatability */
02828       if (!strcasecmp(activateon, "self") || !strcasecmp(activateon, "caller"))
02829          ast_set_flag(feature, AST_FEATURE_FLAG_ONSELF);
02830       else if (!strcasecmp(activateon, "peer") || !strcasecmp(activateon, "callee"))
02831          ast_set_flag(feature, AST_FEATURE_FLAG_ONPEER);
02832       else {
02833          ast_log(LOG_NOTICE, "Invalid 'ActivateOn' specification for feature '%s',"
02834             " must be 'self', or 'peer'\n", var->name);
02835          continue;
02836       }
02837 
02838       if (ast_strlen_zero(activatedby))
02839          ast_set_flag(feature, AST_FEATURE_FLAG_BYBOTH);
02840       else if (!strcasecmp(activatedby, "caller"))
02841          ast_set_flag(feature, AST_FEATURE_FLAG_BYCALLER);
02842       else if (!strcasecmp(activatedby, "callee"))
02843          ast_set_flag(feature, AST_FEATURE_FLAG_BYCALLEE);
02844       else if (!strcasecmp(activatedby, "both"))
02845          ast_set_flag(feature, AST_FEATURE_FLAG_BYBOTH);
02846       else {
02847          ast_log(LOG_NOTICE, "Invalid 'ActivatedBy' specification for feature '%s',"
02848             " must be 'caller', or 'callee', or 'both'\n", var->name);
02849          continue;
02850       }
02851 
02852       ast_register_feature(feature);
02853          
02854       if (option_verbose >= 1)
02855          ast_verbose(VERBOSE_PREFIX_2 "Mapping Feature '%s' to app '%s(%s)' with code '%s'\n", var->name, app, app_args, exten);  
02856    }   
02857    ast_config_destroy(cfg);
02858 
02859    /* Remove the old parking extension */
02860    if (!ast_strlen_zero(old_parking_con) && (con = ast_context_find(old_parking_con))) {
02861       if(ast_context_remove_extension2(con, old_parking_ext, 1, registrar))
02862             notify_metermaids(old_parking_ext, old_parking_con);
02863       if (option_debug)
02864          ast_log(LOG_DEBUG, "Removed old parking extension %s@%s\n", old_parking_ext, old_parking_con);
02865    }
02866    
02867    if (!(con = ast_context_find(parking_con)) && !(con = ast_context_create(NULL, parking_con, registrar))) {
02868       ast_log(LOG_ERROR, "Parking context '%s' does not exist and unable to create\n", parking_con);
02869       return -1;
02870    }
02871    res = ast_add_extension2(con, 1, ast_parking_ext(), 1, NULL, NULL, parkcall, NULL, NULL, registrar);
02872    if (parkaddhints)
02873       park_add_hints(parking_con, parking_start, parking_stop);
02874    if (!res)
02875       notify_metermaids(ast_parking_ext(), parking_con);
02876    return res;
02877 
02878 }
02879 
02880 static char *app_bridge = "Bridge";
02881 static char *bridge_synopsis = "Bridge two channels";
02882 static char *bridge_descrip =
02883 "Usage: Bridge(channel[|options])\n"
02884 "  Allows the ability to bridge two channels via the dialplan.\n"
02885 "The current channel is bridged to the specified 'channel'.\n"
02886 "The following options are supported:\n"
02887 "   p - Play a courtesy tone to 'channel'.\n"
02888 "BRIDGERESULT dial plan variable will contain SUCCESS, FAILURE, LOOP, NONEXISTENT or INCOMPATIBLE.\n";
02889 
02890 enum {
02891    BRIDGE_OPT_PLAYTONE = (1 << 0),
02892 };
02893 
02894 AST_APP_OPTIONS(bridge_exec_options, BEGIN_OPTIONS
02895    AST_APP_OPTION('p', BRIDGE_OPT_PLAYTONE)
02896 END_OPTIONS );
02897 
02898 static int bridge_exec(struct ast_channel *chan, void *data)
02899 {
02900    struct ast_module_user *u;
02901    struct ast_channel *current_dest_chan, *final_dest_chan;
02902    char *tmp_data  = NULL;
02903    struct ast_flags opts = { 0, };
02904    struct ast_bridge_config bconfig = { { 0, }, };
02905 
02906    AST_DECLARE_APP_ARGS(args,
02907       AST_APP_ARG(dest_chan);
02908       AST_APP_ARG(options);
02909    );
02910    
02911    if (ast_strlen_zero(data)) {
02912       ast_log(LOG_WARNING, "Bridge require at least 1 argument specifying the other end of the bridge\n");
02913       return -1;
02914    }
02915    
02916    u = ast_module_user_add(chan);
02917 
02918    tmp_data = ast_strdupa(data);
02919    AST_STANDARD_APP_ARGS(args, tmp_data);
02920    if (!ast_strlen_zero(args.options))
02921       ast_app_parse_options(bridge_exec_options, &opts, NULL, args.options);
02922 
02923    /* avoid bridge with ourselves */
02924    if (!strncmp(chan->name, args.dest_chan, 
02925       strlen(chan->name) < strlen(args.dest_chan) ? 
02926       strlen(chan->name) : strlen(args.dest_chan))) {
02927       ast_log(LOG_WARNING, "Unable to bridge channel %s with itself\n", chan->name);
02928       manager_event(EVENT_FLAG_CALL, "BridgeExec",
02929                "Response: Failed\r\n"
02930                "Reason: Unable to bridge channel to itself\r\n"
02931                "Channel1: %s\r\n"
02932                "Channel2: %s\r\n",
02933                chan->name, args.dest_chan);
02934       pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "LOOP");
02935       ast_module_user_remove(u);
02936       return 0;
02937    }
02938 
02939    /* make sure we have a valid end point */
02940    if (!(current_dest_chan = ast_get_channel_by_name_prefix_locked(args.dest_chan, 
02941       strlen(args.dest_chan)))) {
02942       ast_log(LOG_WARNING, "Bridge failed because channel %s does not exists or we "
02943          "cannot get its lock\n", args.dest_chan);
02944       manager_event(EVENT_FLAG_CALL, "BridgeExec",
02945                "Response: Failed\r\n"
02946                "Reason: Cannot grab end point\r\n"
02947                "Channel1: %s\r\n"
02948                "Channel2: %s\r\n", chan->name, args.dest_chan);
02949       pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "NONEXISTENT");
02950       ast_module_user_remove(u);
02951       return 0;
02952    }
02953    ast_mutex_unlock(&current_dest_chan->lock);
02954 
02955    /* answer the channel if needed */
02956    if (current_dest_chan->_state != AST_STATE_UP)
02957       ast_answer(current_dest_chan);
02958 
02959    /* try to allocate a place holder where current_dest_chan will be placed */
02960    if (!(final_dest_chan = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL, 
02961       NULL, NULL, 0, "Bridge/%s", current_dest_chan->name))) {
02962       ast_log(LOG_WARNING, "Cannot create placeholder channel for chan %s\n", args.dest_chan);
02963       manager_event(EVENT_FLAG_CALL, "BridgeExec",
02964                "Response: Failed\r\n"
02965                "Reason: cannot create placeholder\r\n"
02966                "Channel1: %s\r\n"
02967                "Channel2: %s\r\n", chan->name, args.dest_chan);
02968    }
02969    do_bridge_masquerade(current_dest_chan, final_dest_chan);
02970 
02971    /* now current_dest_chan is a ZOMBIE and with softhangup set to 1 and final_dest_chan is our end point */
02972    /* try to make compatible, send error if we fail */
02973    if (ast_channel_make_compatible(chan, final_dest_chan) < 0) {
02974       ast_log(LOG_WARNING, "Could not make channels %s and %s compatible for bridge\n", chan->name, final_dest_chan->name);
02975       manager_event(EVENT_FLAG_CALL, "BridgeExec",
02976                "Response: Failed\r\n"
02977                "Reason: Could not make channels compatible for bridge\r\n"
02978                "Channel1: %s\r\n"
02979                "Channel2: %s\r\n", chan->name, final_dest_chan->name);
02980       ast_hangup(final_dest_chan); /* may be we should return this channel to the PBX? */
02981       pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "INCOMPATIBLE");
02982       ast_module_user_remove(u);
02983       return 0;
02984    }
02985 
02986    /* Report that the bridge will be successfull */
02987    manager_event(EVENT_FLAG_CALL, "BridgeExec",
02988             "Response: Success\r\n"
02989             "Channel1: %s\r\n"
02990             "Channel2: %s\r\n", chan->name, final_dest_chan->name);
02991 
02992    /* we have 2 valid channels to bridge, now it is just a matter of setting up the bridge config and starting the bridge */  
02993    if (ast_test_flag(&opts, BRIDGE_OPT_PLAYTONE) && !ast_strlen_zero(xfersound)) {
02994       if (!ast_streamfile(final_dest_chan, xfersound, final_dest_chan->language)) {
02995          if (ast_waitstream(final_dest_chan, "") < 0)
02996             ast_log(LOG_WARNING, "Failed to play courtesy tone on %s\n", final_dest_chan->name);
02997       }
02998    }
02999    
03000    /* do the bridge */
03001    ast_bridge_call(chan, final_dest_chan, &bconfig);
03002 
03003    /* the bridge has ended, set BRIDGERESULT to SUCCESS. If the other channel has not been hung up, return it to the PBX */
03004    pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "SUCCESS");
03005    if (!ast_check_hangup(final_dest_chan)) {
03006       if (option_debug) {
03007          ast_log(LOG_DEBUG, "starting new PBX in %s,%s,%d for chan %s\n", 
03008          final_dest_chan->context, final_dest_chan->exten, 
03009          final_dest_chan->priority, final_dest_chan->name);
03010       }
03011 
03012       if (ast_pbx_start(final_dest_chan) != AST_PBX_SUCCESS) {
03013          ast_log(LOG_WARNING, "FAILED continuing PBX on dest chan %s\n", final_dest_chan->name);
03014          ast_hangup(final_dest_chan);
03015       } else if (option_debug)
03016          ast_log(LOG_DEBUG, "SUCCESS continuing PBX on chan %s\n", final_dest_chan->name);
03017    } else {
03018       if (option_debug)
03019          ast_log(LOG_DEBUG, "hangup chan %s since the other endpoint has hung up\n", final_dest_chan->name);
03020       ast_hangup(final_dest_chan);
03021    }
03022 
03023    ast_module_user_remove(u);
03024 
03025    return 0;
03026 }
03027 
03028 static int reload(void)
03029 {
03030    return load_config();
03031 }
03032 
03033 static int load_module(void)
03034 {
03035    int res;
03036 
03037    ast_register_application(app_bridge, bridge_exec, bridge_synopsis, bridge_descrip); 
03038 
03039    memset(parking_ext, 0, sizeof(parking_ext));
03040    memset(parking_con, 0, sizeof(parking_con));
03041 
03042    if ((res = load_config()))
03043       return res;
03044    ast_cli_register_multiple(cli_features, sizeof(cli_features) / sizeof(struct ast_cli_entry));
03045    ast_pthread_create(&parking_thread, NULL, do_parking_thread, NULL);
03046    res = ast_register_application(parkedcall, park_exec, synopsis, descrip);
03047    if (!res)
03048       res = ast_register_application(parkcall, park_call_exec, synopsis2, descrip2);
03049    if (!res) {
03050       ast_manager_register("ParkedCalls", 0, manager_parking_status, "List parked calls");
03051       ast_manager_register2("Park", EVENT_FLAG_CALL, manager_park,
03052          "Park a channel", mandescr_park); 
03053       ast_manager_register2("Bridge", EVENT_FLAG_COMMAND, action_bridge, "Bridge two channels already in the PBX", mandescr_bridge);
03054    }
03055 
03056    res |= ast_devstate_prov_add("Park", metermaidstate);
03057 
03058    return res;
03059 }
03060 
03061 
03062 static int unload_module(void)
03063 {
03064    ast_module_user_hangup_all();
03065 
03066    ast_manager_unregister("ParkedCalls");
03067    ast_manager_unregister("Bridge");
03068    ast_manager_unregister("Park");
03069    ast_cli_unregister_multiple(cli_features, sizeof(cli_features) / sizeof(struct ast_cli_entry));
03070    ast_unregister_application(parkcall);
03071    ast_unregister_application(app_bridge);
03072    ast_devstate_prov_del("Park");
03073    return ast_unregister_application(parkedcall);
03074 }
03075 
03076 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Call Features Resource",
03077       .load = load_module,
03078       .unload = unload_module,
03079       .reload = reload,
03080          );

Generated on Fri Jul 3 20:35:40 2009 for Asterisk - the Open Source PBX by  doxygen 1.5.9