Fri Jul 3 20:35:34 2009

Asterisk developer's documentation


chan_agent.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 
00020 /*! \file
00021  * 
00022  * \brief Implementation of Agents (proxy channel)
00023  *
00024  * \author Mark Spencer <markster@digium.com>
00025  *
00026  * This file is the implementation of Agents modules.
00027  * It is a dynamic module that is loaded by Asterisk. 
00028  * \par See also
00029  * \arg \ref Config_agent
00030  *
00031  * \ingroup channel_drivers
00032  */
00033 /*** MODULEINFO
00034         <depend>chan_local</depend>
00035  ***/
00036 
00037 #include "asterisk.h"
00038 
00039 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
00040 
00041 #include <stdio.h>
00042 #include <string.h>
00043 #include <errno.h>
00044 #include <unistd.h>
00045 #include <sys/socket.h>
00046 #include <stdlib.h>
00047 #include <fcntl.h>
00048 #include <netdb.h>
00049 #include <netinet/in.h>
00050 #include <arpa/inet.h>
00051 #include <sys/signal.h>
00052 
00053 #include "asterisk/lock.h"
00054 #include "asterisk/channel.h"
00055 #include "asterisk/config.h"
00056 #include "asterisk/logger.h"
00057 #include "asterisk/module.h"
00058 #include "asterisk/pbx.h"
00059 #include "asterisk/options.h"
00060 #include "asterisk/lock.h"
00061 #include "asterisk/sched.h"
00062 #include "asterisk/io.h"
00063 #include "asterisk/rtp.h"
00064 #include "asterisk/acl.h"
00065 #include "asterisk/callerid.h"
00066 #include "asterisk/file.h"
00067 #include "asterisk/cli.h"
00068 #include "asterisk/app.h"
00069 #include "asterisk/musiconhold.h"
00070 #include "asterisk/manager.h"
00071 #include "asterisk/features.h"
00072 #include "asterisk/utils.h"
00073 #include "asterisk/causes.h"
00074 #include "asterisk/astdb.h"
00075 #include "asterisk/devicestate.h"
00076 #include "asterisk/monitor.h"
00077 #include "asterisk/stringfields.h"
00078 
00079 static const char tdesc[] = "Call Agent Proxy Channel";
00080 static const char config[] = "agents.conf";
00081 
00082 static const char app[] = "AgentLogin";
00083 static const char app2[] = "AgentCallbackLogin";
00084 static const char app3[] = "AgentMonitorOutgoing";
00085 
00086 static const char synopsis[] = "Call agent login";
00087 static const char synopsis2[] = "Call agent callback login";
00088 static const char synopsis3[] = "Record agent's outgoing call";
00089 
00090 static const char descrip[] =
00091 "  AgentLogin([AgentNo][|options]):\n"
00092 "Asks the agent to login to the system.  Always returns -1.  While\n"
00093 "logged in, the agent can receive calls and will hear a 'beep'\n"
00094 "when a new call comes in. The agent can dump the call by pressing\n"
00095 "the star key.\n"
00096 "The option string may contain zero or more of the following characters:\n"
00097 "      's' -- silent login - do not announce the login ok segment after agent logged in/off\n";
00098 
00099 static const char descrip2[] =
00100 "  AgentCallbackLogin([AgentNo][|[options][|[exten]@context]]):\n"
00101 "Asks the agent to login to the system with callback.\n"
00102 "The agent's callback extension is called (optionally with the specified\n"
00103 "context).\n"
00104 "The option string may contain zero or more of the following characters:\n"
00105 "      's' -- silent login - do not announce the login ok segment agent logged in/off\n";
00106 
00107 static const char descrip3[] =
00108 "  AgentMonitorOutgoing([options]):\n"
00109 "Tries to figure out the id of the agent who is placing outgoing call based on\n"
00110 "comparison of the callerid of the current interface and the global variable \n"
00111 "placed by the AgentCallbackLogin application. That's why it should be used only\n"
00112 "with the AgentCallbackLogin app. Uses the monitoring functions in chan_agent \n"
00113 "instead of Monitor application. That have to be configured in the agents.conf file.\n"
00114 "\nReturn value:\n"
00115 "Normally the app returns 0 unless the options are passed. Also if the callerid or\n"
00116 "the agentid are not specified it'll look for n+101 priority.\n"
00117 "\nOptions:\n"
00118 "  'd' - make the app return -1 if there is an error condition and there is\n"
00119 "        no extension n+101\n"
00120 "  'c' - change the CDR so that the source of the call is 'Agent/agent_id'\n"
00121 "  'n' - don't generate the warnings when there is no callerid or the\n"
00122 "        agentid is not known.\n"
00123 "             It's handy if you want to have one context for agent and non-agent calls.\n";
00124 
00125 static const char mandescr_agents[] =
00126 "Description: Will list info about all possible agents.\n"
00127 "Variables: NONE\n";
00128 
00129 static const char mandescr_agent_logoff[] =
00130 "Description: Sets an agent as no longer logged in.\n"
00131 "Variables: (Names marked with * are required)\n"
00132 "  *Agent: Agent ID of the agent to log off\n"
00133 "  Soft: Set to 'true' to not hangup existing calls\n";
00134 
00135 static const char mandescr_agent_callback_login[] =
00136 "Description: Sets an agent as logged in with callback.\n"
00137 "Variables: (Names marked with * are required)\n"
00138 "  *Agent: Agent ID of the agent to login\n"
00139 "  *Exten: Extension to use for callback\n"
00140 "  Context: Context to use for callback\n"
00141 "  AckCall: Set to 'true' to require an acknowledgement by '#' when agent is called back\n"
00142 "  WrapupTime: the minimum amount of time after disconnecting before the caller can receive a new call\n";
00143 
00144 static char moh[80] = "default";
00145 
00146 #define AST_MAX_AGENT   80                          /*!< Agent ID or Password max length */
00147 #define AST_MAX_BUF  256
00148 #define AST_MAX_FILENAME_LEN  256
00149 
00150 static const char pa_family[] = "Agents";          /*!< Persistent Agents astdb family */
00151 #define PA_MAX_LEN 2048                             /*!< The maximum length of each persistent member agent database entry */
00152 
00153 static int persistent_agents = 0;                   /*!< queues.conf [general] option */
00154 static void dump_agents(void);
00155 
00156 static ast_group_t group;
00157 static int autologoff;
00158 static int wrapuptime;
00159 static int ackcall;
00160 static int endcall;
00161 static int multiplelogin = 1;
00162 static int autologoffunavail = 0;
00163 
00164 static int maxlogintries = 3;
00165 static char agentgoodbye[AST_MAX_FILENAME_LEN] = "vm-goodbye";
00166 
00167 static int recordagentcalls = 0;
00168 static char recordformat[AST_MAX_BUF] = "";
00169 static char recordformatext[AST_MAX_BUF] = "";
00170 static char urlprefix[AST_MAX_BUF] = "";
00171 static char savecallsin[AST_MAX_BUF] = "";
00172 static int updatecdr = 0;
00173 static char beep[AST_MAX_BUF] = "beep";
00174 
00175 #define GETAGENTBYCALLERID "AGENTBYCALLERID"
00176 
00177 /*! \brief Structure representing an agent.  */
00178 struct agent_pvt {
00179    ast_mutex_t lock;              /*!< Channel private lock */
00180    int dead;                      /*!< Poised for destruction? */
00181    int pending;                   /*!< Not a real agent -- just pending a match */
00182    int abouttograb;               /*!< About to grab */
00183    int autologoff;                /*!< Auto timeout time */
00184    int ackcall;                   /*!< ackcall */
00185    int deferlogoff;               /*!< Defer logoff to hangup */
00186    time_t loginstart;             /*!< When agent first logged in (0 when logged off) */
00187    time_t start;                  /*!< When call started */
00188    struct timeval lastdisc;       /*!< When last disconnected */
00189    int wrapuptime;                /*!< Wrapup time in ms */
00190    ast_group_t group;             /*!< Group memberships */
00191    int acknowledged;              /*!< Acknowledged */
00192    char moh[80];                  /*!< Which music on hold */
00193    char agent[AST_MAX_AGENT];     /*!< Agent ID */
00194    char password[AST_MAX_AGENT];  /*!< Password for Agent login */
00195    char name[AST_MAX_AGENT];
00196    int inherited_devicestate;     /*!< Does the underlying channel have a devicestate to pass? */
00197    ast_mutex_t app_lock;          /**< Synchronization between owning applications */
00198    volatile pthread_t owning_app; /**< Owning application thread id */
00199    volatile int app_sleep_cond;   /**< Sleep condition for the login app */
00200    struct ast_channel *owner;     /**< Agent */
00201    char loginchan[80];            /**< channel they logged in from */
00202    char logincallerid[80];        /**< Caller ID they had when they logged in */
00203    struct ast_channel *chan;      /**< Channel we use */
00204    AST_LIST_ENTRY(agent_pvt) list;  /**< Next Agent in the linked list. */
00205 };
00206 
00207 static AST_LIST_HEAD_STATIC(agents, agent_pvt); /*!< Holds the list of agents (loaded form agents.conf). */
00208 
00209 #define CHECK_FORMATS(ast, p) do { \
00210    if (p->chan) {\
00211       if (ast->nativeformats != p->chan->nativeformats) { \
00212          ast_log(LOG_DEBUG, "Native formats changing from %d to %d\n", ast->nativeformats, p->chan->nativeformats); \
00213          /* Native formats changed, reset things */ \
00214          ast->nativeformats = p->chan->nativeformats; \
00215          ast_log(LOG_DEBUG, "Resetting read to %d and write to %d\n", ast->readformat, ast->writeformat);\
00216          ast_set_read_format(ast, ast->readformat); \
00217          ast_set_write_format(ast, ast->writeformat); \
00218       } \
00219       if (p->chan->readformat != ast->rawreadformat && !p->chan->generator)  \
00220          ast_set_read_format(p->chan, ast->rawreadformat); \
00221       if (p->chan->writeformat != ast->rawwriteformat && !p->chan->generator) \
00222          ast_set_write_format(p->chan, ast->rawwriteformat); \
00223    } \
00224 } while(0)
00225 
00226 /*! \brief Cleanup moves all the relevant FD's from the 2nd to the first, but retains things
00227    properly for a timingfd XXX This might need more work if agents were logged in as agents or other
00228    totally impractical combinations XXX */
00229 
00230 #define CLEANUP(ast, p) do { \
00231    int x; \
00232    if (p->chan) { \
00233       for (x=0;x<AST_MAX_FDS;x++) {\
00234          if (x != AST_TIMING_FD) \
00235             ast->fds[x] = p->chan->fds[x]; \
00236       } \
00237       ast->fds[AST_AGENT_FD] = p->chan->fds[AST_TIMING_FD]; \
00238    } \
00239 } while(0)
00240 
00241 /*--- Forward declarations */
00242 static struct ast_channel *agent_request(const char *type, int format, void *data, int *cause);
00243 static int agent_devicestate(void *data);
00244 static void agent_logoff_maintenance(struct agent_pvt *p, char *loginchan, long logintime, const char *uniqueid, char *logcommand);
00245 static int agent_digit_begin(struct ast_channel *ast, char digit);
00246 static int agent_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
00247 static int agent_call(struct ast_channel *ast, char *dest, int timeout);
00248 static int agent_hangup(struct ast_channel *ast);
00249 static int agent_answer(struct ast_channel *ast);
00250 static struct ast_frame *agent_read(struct ast_channel *ast);
00251 static int agent_write(struct ast_channel *ast, struct ast_frame *f);
00252 static int agent_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen);
00253 static int agent_sendtext(struct ast_channel *ast, const char *text);
00254 static int agent_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
00255 static int agent_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
00256 static struct ast_channel *agent_bridgedchannel(struct ast_channel *chan, struct ast_channel *bridge);
00257 static void set_agentbycallerid(const char *callerid, const char *agent);
00258 static struct ast_channel* agent_get_base_channel(struct ast_channel *chan);
00259 static int agent_set_base_channel(struct ast_channel *chan, struct ast_channel *base);
00260 
00261 /*! \brief Channel interface description for PBX integration */
00262 static const struct ast_channel_tech agent_tech = {
00263    .type = "Agent",
00264    .description = tdesc,
00265    .capabilities = -1,
00266    .requester = agent_request,
00267    .devicestate = agent_devicestate,
00268    .send_digit_begin = agent_digit_begin,
00269    .send_digit_end = agent_digit_end,
00270    .call = agent_call,
00271    .hangup = agent_hangup,
00272    .answer = agent_answer,
00273    .read = agent_read,
00274    .write = agent_write,
00275    .write_video = agent_write,
00276    .send_html = agent_sendhtml,
00277    .send_text = agent_sendtext,
00278    .exception = agent_read,
00279    .indicate = agent_indicate,
00280    .fixup = agent_fixup,
00281    .bridged_channel = agent_bridgedchannel,
00282    .get_base_channel = agent_get_base_channel,
00283    .set_base_channel = agent_set_base_channel,
00284 };
00285 
00286 static int agent_devicestate_cb(const char *dev, int state, void *data)
00287 {
00288    int res, i;
00289    struct agent_pvt *p;
00290    char basename[AST_CHANNEL_NAME], *tmp;
00291 
00292    /* Skip Agent status */
00293    if (!strncasecmp(dev, "Agent/", 6)) {
00294       return 0;
00295    }
00296 
00297    /* Try to be safe, but don't deadlock */
00298    for (i = 0; i < 10; i++) {
00299       if ((res = AST_LIST_TRYLOCK(&agents)) == 0) {
00300          break;
00301       }
00302    }
00303    if (res) {
00304       return -1;
00305    }
00306 
00307    AST_LIST_TRAVERSE(&agents, p, list) {
00308       ast_mutex_lock(&p->lock);
00309       if (p->chan) {
00310          ast_copy_string(basename, p->chan->name, sizeof(basename));
00311          if ((tmp = strrchr(basename, '-'))) {
00312             *tmp = '\0';
00313          }
00314          if (strcasecmp(p->chan->name, dev) == 0 || strcasecmp(basename, dev) == 0) {
00315             p->inherited_devicestate = state;
00316             ast_device_state_changed("Agent/%s", p->agent);
00317          }
00318       }
00319       ast_mutex_unlock(&p->lock);
00320    }
00321    AST_LIST_UNLOCK(&agents);
00322    return 0;
00323 }
00324 
00325 /*!
00326  * Adds an agent to the global list of agents.
00327  *
00328  * \param agent A string with the username, password and real name of an agent. As defined in agents.conf. Example: "13,169,John Smith"
00329  * \param pending If it is pending or not.
00330  * @return The just created agent.
00331  * \sa agent_pvt, agents.
00332  */
00333 static struct agent_pvt *add_agent(char *agent, int pending)
00334 {
00335    char *parse;
00336    AST_DECLARE_APP_ARGS(args,
00337       AST_APP_ARG(agt);
00338       AST_APP_ARG(password);
00339       AST_APP_ARG(name);
00340    );
00341    char *password = NULL;
00342    char *name = NULL;
00343    char *agt = NULL;
00344    struct agent_pvt *p;
00345 
00346    parse = ast_strdupa(agent);
00347 
00348    /* Extract username (agt), password and name from agent (args). */
00349    AST_NONSTANDARD_APP_ARGS(args, parse, ',');
00350 
00351    if(args.argc == 0) {
00352       ast_log(LOG_WARNING, "A blank agent line!\n");
00353       return NULL;
00354    }
00355 
00356    if(ast_strlen_zero(args.agt) ) {
00357       ast_log(LOG_WARNING, "An agent line with no agentid!\n");
00358       return NULL;
00359    } else
00360       agt = args.agt;
00361 
00362    if(!ast_strlen_zero(args.password)) {
00363       password = args.password;
00364       while (*password && *password < 33) password++;
00365    }
00366    if(!ast_strlen_zero(args.name)) {
00367       name = args.name;
00368       while (*name && *name < 33) name++;
00369    }
00370    
00371    /* Are we searching for the agent here ? To see if it exists already ? */
00372    AST_LIST_TRAVERSE(&agents, p, list) {
00373       if (!pending && !strcmp(p->agent, agt))
00374          break;
00375    }
00376    if (!p) {
00377       // Build the agent.
00378       if (!(p = ast_calloc(1, sizeof(*p))))
00379          return NULL;
00380       ast_copy_string(p->agent, agt, sizeof(p->agent));
00381       ast_mutex_init(&p->lock);
00382       ast_mutex_init(&p->app_lock);
00383       p->owning_app = (pthread_t) -1;
00384       p->app_sleep_cond = 1;
00385       p->group = group;
00386       p->pending = pending;
00387       p->inherited_devicestate = -1;
00388       AST_LIST_INSERT_TAIL(&agents, p, list);
00389    }
00390    
00391    ast_copy_string(p->password, password ? password : "", sizeof(p->password));
00392    ast_copy_string(p->name, name ? name : "", sizeof(p->name));
00393    ast_copy_string(p->moh, moh, sizeof(p->moh));
00394    p->ackcall = ackcall;
00395    p->autologoff = autologoff;
00396 
00397    /* If someone reduces the wrapuptime and reloads, we want it
00398     * to change the wrapuptime immediately on all calls */
00399    if (p->wrapuptime > wrapuptime) {
00400       struct timeval now = ast_tvnow();
00401       /* XXX check what is this exactly */
00402 
00403       /* We won't be pedantic and check the tv_usec val */
00404       if (p->lastdisc.tv_sec > (now.tv_sec + wrapuptime/1000)) {
00405          p->lastdisc.tv_sec = now.tv_sec + wrapuptime/1000;
00406          p->lastdisc.tv_usec = now.tv_usec;
00407       }
00408    }
00409    p->wrapuptime = wrapuptime;
00410 
00411    if (pending)
00412       p->dead = 1;
00413    else
00414       p->dead = 0;
00415    return p;
00416 }
00417 
00418 /*!
00419  * Deletes an agent after doing some clean up.
00420  * Further documentation: How safe is this function ? What state should the agent be to be cleaned.
00421  * \param p Agent to be deleted.
00422  * \returns Always 0.
00423  */
00424 static int agent_cleanup(struct agent_pvt *p)
00425 {
00426    struct ast_channel *chan = p->owner;
00427    p->owner = NULL;
00428    chan->tech_pvt = NULL;
00429    p->app_sleep_cond = 1;
00430    /* Release ownership of the agent to other threads (presumably running the login app). */
00431    ast_mutex_unlock(&p->app_lock);
00432    if (chan)
00433       ast_channel_free(chan);
00434    if (p->dead) {
00435       ast_mutex_destroy(&p->lock);
00436       ast_mutex_destroy(&p->app_lock);
00437       free(p);
00438         }
00439    return 0;
00440 }
00441 
00442 static int check_availability(struct agent_pvt *newlyavailable, int needlock);
00443 
00444 static int agent_answer(struct ast_channel *ast)
00445 {
00446    ast_log(LOG_WARNING, "Huh?  Agent is being asked to answer?\n");
00447    return -1;
00448 }
00449 
00450 static int __agent_start_monitoring(struct ast_channel *ast, struct agent_pvt *p, int needlock)
00451 {
00452    char tmp[AST_MAX_BUF],tmp2[AST_MAX_BUF], *pointer;
00453    char filename[AST_MAX_BUF];
00454    int res = -1;
00455    if (!p)
00456       return -1;
00457    if (!ast->monitor) {
00458       snprintf(filename, sizeof(filename), "agent-%s-%s",p->agent, ast->uniqueid);
00459       /* substitute . for - */
00460       if ((pointer = strchr(filename, '.')))
00461          *pointer = '-';
00462       snprintf(tmp, sizeof(tmp), "%s%s", savecallsin, filename);
00463       ast_monitor_start(ast, recordformat, tmp, needlock);
00464       ast_monitor_setjoinfiles(ast, 1);
00465       snprintf(tmp2, sizeof(tmp2), "%s%s.%s", urlprefix, filename, recordformatext);
00466 #if 0
00467       ast_verbose("name is %s, link is %s\n",tmp, tmp2);
00468 #endif
00469       if (!ast->cdr)
00470          ast->cdr = ast_cdr_alloc();
00471       ast_cdr_setuserfield(ast, tmp2);
00472       res = 0;
00473    } else
00474       ast_log(LOG_ERROR, "Recording already started on that call.\n");
00475    return res;
00476 }
00477 
00478 static int agent_start_monitoring(struct ast_channel *ast, int needlock)
00479 {
00480    return __agent_start_monitoring(ast, ast->tech_pvt, needlock);
00481 }
00482 
00483 static struct ast_frame *agent_read(struct ast_channel *ast)
00484 {
00485    struct agent_pvt *p = ast->tech_pvt;
00486    struct ast_frame *f = NULL;
00487    static struct ast_frame answer_frame = { AST_FRAME_CONTROL, AST_CONTROL_ANSWER };
00488    const char *status;
00489    ast_mutex_lock(&p->lock); 
00490    CHECK_FORMATS(ast, p);
00491    if (p->chan) {
00492       ast_copy_flags(p->chan, ast, AST_FLAG_EXCEPTION);
00493       p->chan->fdno = (ast->fdno == AST_AGENT_FD) ? AST_TIMING_FD : ast->fdno;
00494       f = ast_read(p->chan);
00495    } else
00496       f = &ast_null_frame;
00497    if (!f) {
00498       /* If there's a channel, hang it up (if it's on a callback) make it NULL */
00499       if (p->chan) {
00500          p->chan->_bridge = NULL;
00501          /* Note that we don't hangup if it's not a callback because Asterisk will do it
00502             for us when the PBX instance that called login finishes */
00503          if (!ast_strlen_zero(p->loginchan)) {
00504             if (p->chan)
00505                ast_log(LOG_DEBUG, "Bridge on '%s' being cleared (2)\n", p->chan->name);
00506             if (p->owner->_state != AST_STATE_UP) {
00507                int howlong = time(NULL) - p->start;
00508                if (p->autologoff && howlong > p->autologoff) {
00509                   long logintime = time(NULL) - p->loginstart;
00510                   p->loginstart = 0;
00511                      ast_log(LOG_NOTICE, "Agent '%s' didn't answer/confirm within %d seconds (waited %d)\n", p->name, p->autologoff, howlong);
00512                   agent_logoff_maintenance(p, p->loginchan, logintime, ast->uniqueid, "Autologoff");
00513                   if (persistent_agents)
00514                      dump_agents();
00515                }
00516             }
00517             status = pbx_builtin_getvar_helper(p->chan, "CHANLOCALSTATUS");
00518             if (autologoffunavail && status && !strcasecmp(status, "CHANUNAVAIL")) {
00519                long logintime = time(NULL) - p->loginstart;
00520                p->loginstart = 0;
00521                ast_log(LOG_NOTICE, "Agent read: '%s' is not available now, auto logoff\n", p->name);
00522                agent_logoff_maintenance(p, p->loginchan, logintime, ast->uniqueid, "Chanunavail");
00523             }
00524             ast_hangup(p->chan);
00525             if (p->wrapuptime && p->acknowledged)
00526                p->lastdisc = ast_tvadd(ast_tvnow(), ast_samp2tv(p->wrapuptime, 1000));
00527          }
00528          p->chan = NULL;
00529          p->inherited_devicestate = -1;
00530          ast_device_state_changed("Agent/%s", p->agent);
00531          p->acknowledged = 0;
00532       }
00533    } else {
00534       /* if acknowledgement is not required, and the channel is up, we may have missed
00535          an AST_CONTROL_ANSWER (if there was one), so mark the call acknowledged anyway */
00536       if (!p->ackcall && !p->acknowledged && p->chan && (p->chan->_state == AST_STATE_UP))
00537          p->acknowledged = 1;
00538       switch (f->frametype) {
00539       case AST_FRAME_CONTROL:
00540          if (f->subclass == AST_CONTROL_ANSWER) {
00541             if (p->ackcall) {
00542                if (option_verbose > 2)
00543                   ast_verbose(VERBOSE_PREFIX_3 "%s answered, waiting for '#' to acknowledge\n", p->chan->name);
00544                /* Don't pass answer along */
00545                ast_frfree(f);
00546                f = &ast_null_frame;
00547             } else {
00548                p->acknowledged = 1;
00549                /* Use the builtin answer frame for the 
00550                   recording start check below. */
00551                ast_frfree(f);
00552                f = &answer_frame;
00553             }
00554          }
00555          break;
00556       case AST_FRAME_DTMF_BEGIN:
00557          /*ignore DTMF begin's as it can cause issues with queue announce files*/
00558          if((!p->acknowledged && f->subclass == '#') || (f->subclass == '*' && endcall)){
00559             ast_frfree(f);
00560             f = &ast_null_frame;
00561          }
00562          break;
00563       case AST_FRAME_DTMF_END:
00564          if (!p->acknowledged && (f->subclass == '#')) {
00565             if (option_verbose > 2)
00566                ast_verbose(VERBOSE_PREFIX_3 "%s acknowledged\n", p->chan->name);
00567             p->acknowledged = 1;
00568             ast_frfree(f);
00569             f = &answer_frame;
00570          } else if (f->subclass == '*' && endcall) {
00571             /* terminates call */
00572             ast_frfree(f);
00573             f = NULL;
00574          }
00575          break;
00576       case AST_FRAME_VOICE:
00577       case AST_FRAME_VIDEO:
00578          /* don't pass voice or video until the call is acknowledged */
00579          if (!p->acknowledged) {
00580             ast_frfree(f);
00581             f = &ast_null_frame;
00582          }
00583       default:
00584          /* pass everything else on through */
00585          break;
00586       }
00587    }
00588 
00589    CLEANUP(ast,p);
00590    if (p->chan && !p->chan->_bridge) {
00591       if (strcasecmp(p->chan->tech->type, "Local")) {
00592          p->chan->_bridge = ast;
00593          if (p->chan)
00594             ast_log(LOG_DEBUG, "Bridge on '%s' being set to '%s' (3)\n", p->chan->name, p->chan->_bridge->name);
00595       }
00596    }
00597    ast_mutex_unlock(&p->lock);
00598    if (recordagentcalls && f == &answer_frame)
00599       agent_start_monitoring(ast,0);
00600    return f;
00601 }
00602 
00603 static int agent_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
00604 {
00605    struct agent_pvt *p = ast->tech_pvt;
00606    int res = -1;
00607    ast_mutex_lock(&p->lock);
00608    if (p->chan) 
00609       res = ast_channel_sendhtml(p->chan, subclass, data, datalen);
00610    ast_mutex_unlock(&p->lock);
00611    return res;
00612 }
00613 
00614 static int agent_sendtext(struct ast_channel *ast, const char *text)
00615 {
00616    struct agent_pvt *p = ast->tech_pvt;
00617    int res = -1;
00618    ast_mutex_lock(&p->lock);
00619    if (p->chan) 
00620       res = ast_sendtext(p->chan, text);
00621    ast_mutex_unlock(&p->lock);
00622    return res;
00623 }
00624 
00625 static int agent_write(struct ast_channel *ast, struct ast_frame *f)
00626 {
00627    struct agent_pvt *p = ast->tech_pvt;
00628    int res = -1;
00629    CHECK_FORMATS(ast, p);
00630    ast_mutex_lock(&p->lock);
00631    if (!p->chan) 
00632       res = 0;
00633    else {
00634       if ((f->frametype != AST_FRAME_VOICE) ||
00635           (f->frametype != AST_FRAME_VIDEO) ||
00636           (f->subclass == p->chan->writeformat)) {
00637          res = ast_write(p->chan, f);
00638       } else {
00639          ast_log(LOG_DEBUG, "Dropping one incompatible %s frame on '%s' to '%s'\n", 
00640             f->frametype == AST_FRAME_VOICE ? "audio" : "video",
00641             ast->name, p->chan->name);
00642          res = 0;
00643       }
00644    }
00645    CLEANUP(ast, p);
00646    ast_mutex_unlock(&p->lock);
00647    return res;
00648 }
00649 
00650 static int agent_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
00651 {
00652    struct agent_pvt *p = newchan->tech_pvt;
00653    ast_mutex_lock(&p->lock);
00654    if (p->owner != oldchan) {
00655       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
00656       ast_mutex_unlock(&p->lock);
00657       return -1;
00658    }
00659    p->owner = newchan;
00660    ast_mutex_unlock(&p->lock);
00661    return 0;
00662 }
00663 
00664 static int agent_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
00665 {
00666    struct agent_pvt *p = ast->tech_pvt;
00667    int res = -1;
00668    ast_mutex_lock(&p->lock);
00669    if (p->chan && !ast_check_hangup(p->chan)) {
00670       while (ast_channel_trylock(p->chan)) {
00671          ast_channel_unlock(ast);
00672          usleep(1);
00673          ast_channel_lock(ast);
00674       }
00675       res = p->chan->tech->indicate ? p->chan->tech->indicate(p->chan, condition, data, datalen) : -1;
00676       ast_channel_unlock(p->chan);
00677    } else
00678       res = 0;
00679    ast_mutex_unlock(&p->lock);
00680    return res;
00681 }
00682 
00683 static int agent_digit_begin(struct ast_channel *ast, char digit)
00684 {
00685    struct agent_pvt *p = ast->tech_pvt;
00686    ast_mutex_lock(&p->lock);
00687    if (p->chan) {
00688       ast_senddigit_begin(p->chan, digit);
00689    }
00690    ast_mutex_unlock(&p->lock);
00691    return 0;
00692 }
00693 
00694 static int agent_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
00695 {
00696    struct agent_pvt *p = ast->tech_pvt;
00697    ast_mutex_lock(&p->lock);
00698    if (p->chan) {
00699       ast_senddigit_end(p->chan, digit, duration);
00700    }
00701    ast_mutex_unlock(&p->lock);
00702    return 0;
00703 }
00704 
00705 static int agent_call(struct ast_channel *ast, char *dest, int timeout)
00706 {
00707    struct agent_pvt *p = ast->tech_pvt;
00708    int res = -1;
00709    int newstate=0;
00710    ast_mutex_lock(&p->lock);
00711    p->acknowledged = 0;
00712    if (!p->chan) {
00713       if (p->pending) {
00714          ast_log(LOG_DEBUG, "Pretending to dial on pending agent\n");
00715          newstate = AST_STATE_DIALING;
00716          res = 0;
00717       } else {
00718          ast_log(LOG_NOTICE, "Whoa, they hung up between alloc and call...  what are the odds of that?\n");
00719          res = -1;
00720       }
00721       ast_mutex_unlock(&p->lock);
00722       if (newstate)
00723          ast_setstate(ast, newstate);
00724       return res;
00725    } else if (!ast_strlen_zero(p->loginchan)) {
00726       time(&p->start);
00727       /* Call on this agent */
00728       if (option_verbose > 2)
00729          ast_verbose(VERBOSE_PREFIX_3 "outgoing agentcall, to agent '%s', on '%s'\n", p->agent, p->chan->name);
00730       ast_set_callerid(p->chan,
00731          ast->cid.cid_num, ast->cid.cid_name, NULL);
00732       ast_channel_inherit_variables(ast, p->chan);
00733       res = ast_call(p->chan, p->loginchan, 0);
00734       CLEANUP(ast,p);
00735       ast_mutex_unlock(&p->lock);
00736       return res;
00737    }
00738    if (option_verbose > 2)
00739       ast_verbose(VERBOSE_PREFIX_3 "agent_call, call to agent '%s' call on '%s'\n", p->agent, p->chan->name);
00740    if (option_debug > 2)
00741       ast_log(LOG_DEBUG, "Playing beep, lang '%s'\n", p->chan->language);
00742    res = ast_streamfile(p->chan, beep, p->chan->language);
00743    if (option_debug > 2)
00744       ast_log(LOG_DEBUG, "Played beep, result '%d'\n", res);
00745    if (!res) {
00746       res = ast_waitstream(p->chan, "");
00747       if (option_debug > 2)
00748          ast_log(LOG_DEBUG, "Waited for stream, result '%d'\n", res);
00749    }
00750    if (!res) {
00751       res = ast_set_read_format(p->chan, ast_best_codec(p->chan->nativeformats));
00752       if (option_debug > 2)
00753          ast_log(LOG_DEBUG, "Set read format, result '%d'\n", res);
00754       if (res)
00755          ast_log(LOG_WARNING, "Unable to set read format to %s\n", ast_getformatname(ast_best_codec(p->chan->nativeformats)));
00756    } else {
00757       /* Agent hung-up */
00758       p->chan = NULL;
00759       p->inherited_devicestate = -1;
00760       ast_device_state_changed("Agent/%s", p->agent);
00761    }
00762 
00763    if (!res) {
00764       res = ast_set_write_format(p->chan, ast_best_codec(p->chan->nativeformats));
00765       if (option_debug > 2)
00766          ast_log(LOG_DEBUG, "Set write format, result '%d'\n", res);
00767       if (res)
00768          ast_log(LOG_WARNING, "Unable to set write format to %s\n", ast_getformatname(ast_best_codec(p->chan->nativeformats)));
00769    }
00770    if(!res) {
00771       /* Call is immediately up, or might need ack */
00772       if (p->ackcall > 1)
00773          newstate = AST_STATE_RINGING;
00774       else {
00775          newstate = AST_STATE_UP;
00776          if (recordagentcalls)
00777             agent_start_monitoring(ast, 0);
00778          p->acknowledged = 1;
00779       }
00780       res = 0;
00781    }
00782    CLEANUP(ast, p);
00783    ast_mutex_unlock(&p->lock);
00784    if (newstate)
00785       ast_setstate(ast, newstate);
00786    return res;
00787 }
00788 
00789 /*! \brief store/clear the global variable that stores agentid based on the callerid */
00790 static void set_agentbycallerid(const char *callerid, const char *agent)
00791 {
00792    char buf[AST_MAX_BUF];
00793 
00794    /* if there is no Caller ID, nothing to do */
00795    if (ast_strlen_zero(callerid))
00796       return;
00797 
00798    snprintf(buf, sizeof(buf), "%s_%s", GETAGENTBYCALLERID, callerid);
00799    pbx_builtin_setvar_helper(NULL, buf, agent);
00800 }
00801 
00802 /*! \brief return the channel or base channel if one exists.  This function assumes the channel it is called on is already locked */
00803 struct ast_channel* agent_get_base_channel(struct ast_channel *chan)
00804 {
00805    struct agent_pvt *p = NULL;
00806    struct ast_channel *base = chan;
00807 
00808    /* chan is locked by the calling function */
00809    if (!chan || !chan->tech_pvt) {
00810       ast_log(LOG_ERROR, "whoa, you need a channel (0x%ld) with a tech_pvt (0x%ld) to get a base channel.\n", (long)chan, (chan)?(long)chan->tech_pvt:(long)NULL);
00811       return NULL;
00812    }
00813    p = chan->tech_pvt;
00814    if (p->chan) 
00815       base = p->chan;
00816    return base;
00817 }
00818 
00819 int agent_set_base_channel(struct ast_channel *chan, struct ast_channel *base)
00820 {
00821    struct agent_pvt *p = NULL;
00822    
00823    if (!chan || !base) {
00824       ast_log(LOG_ERROR, "whoa, you need a channel (0x%ld) and a base channel (0x%ld) for setting.\n", (long)chan, (long)base);
00825       return -1;
00826    }
00827    p = chan->tech_pvt;
00828    if (!p) {
00829       ast_log(LOG_ERROR, "whoa, channel %s is missing his tech_pvt structure!!.\n", chan->name);
00830       return -1;
00831    }
00832    p->chan = base;
00833    return 0;
00834 }
00835 
00836 static int agent_hangup(struct ast_channel *ast)
00837 {
00838    struct agent_pvt *p = ast->tech_pvt;
00839    int howlong = 0;
00840    const char *status;
00841    ast_mutex_lock(&p->lock);
00842    p->owner = NULL;
00843    ast->tech_pvt = NULL;
00844    p->app_sleep_cond = 1;
00845    p->acknowledged = 0;
00846 
00847    /* if they really are hung up then set start to 0 so the test
00848     * later if we're called on an already downed channel
00849     * doesn't cause an agent to be logged out like when
00850     * agent_request() is followed immediately by agent_hangup()
00851     * as in apps/app_chanisavail.c:chanavail_exec()
00852     */
00853 
00854    if (option_debug)
00855       ast_log(LOG_DEBUG, "Hangup called for state %s\n", ast_state2str(ast->_state));
00856    if (p->start && (ast->_state != AST_STATE_UP)) {
00857       howlong = time(NULL) - p->start;
00858       p->start = 0;
00859    } else if (ast->_state == AST_STATE_RESERVED) 
00860       howlong = 0;
00861    else
00862       p->start = 0; 
00863    if (p->chan) {
00864       p->chan->_bridge = NULL;
00865       /* If they're dead, go ahead and hang up on the agent now */
00866       if (!ast_strlen_zero(p->loginchan)) {
00867          /* Store last disconnect time */
00868          if (p->wrapuptime)
00869             p->lastdisc = ast_tvadd(ast_tvnow(), ast_samp2tv(p->wrapuptime, 1000));
00870          else
00871             p->lastdisc = ast_tv(0,0);
00872          if (p->chan) {
00873             status = pbx_builtin_getvar_helper(p->chan, "CHANLOCALSTATUS");
00874             if (autologoffunavail && status && !strcasecmp(status, "CHANUNAVAIL")) {
00875                long logintime = time(NULL) - p->loginstart;
00876                p->loginstart = 0;
00877                ast_log(LOG_NOTICE, "Agent hangup: '%s' is not available now, auto logoff\n", p->name);
00878                agent_logoff_maintenance(p, p->loginchan, logintime, ast->uniqueid, "Chanunavail");
00879             }
00880             /* Recognize the hangup and pass it along immediately */
00881             ast_hangup(p->chan);
00882             p->chan = NULL;
00883             p->inherited_devicestate = -1;
00884             ast_device_state_changed("Agent/%s", p->agent);
00885          }
00886          ast_log(LOG_DEBUG, "Hungup, howlong is %d, autologoff is %d\n", howlong, p->autologoff);
00887          if ((p->deferlogoff) || (howlong && p->autologoff && (howlong > p->autologoff))) {
00888             long logintime = time(NULL) - p->loginstart;
00889             p->loginstart = 0;
00890             if (!p->deferlogoff)
00891                ast_log(LOG_NOTICE, "Agent '%s' didn't answer/confirm within %d seconds (waited %d)\n", p->name, p->autologoff, howlong);
00892             p->deferlogoff = 0;
00893             agent_logoff_maintenance(p, p->loginchan, logintime, ast->uniqueid, "Autologoff");
00894             if (persistent_agents)
00895                dump_agents();
00896          }
00897       } else if (p->dead) {
00898          ast_channel_lock(p->chan);
00899          ast_softhangup(p->chan, AST_SOFTHANGUP_EXPLICIT);
00900          ast_channel_unlock(p->chan);
00901       } else if (p->loginstart) {
00902          ast_channel_lock(p->chan);
00903          ast_indicate_data(p->chan, AST_CONTROL_HOLD, 
00904             S_OR(p->moh, NULL),
00905             !ast_strlen_zero(p->moh) ? strlen(p->moh) + 1 : 0);
00906          ast_channel_unlock(p->chan);
00907       }
00908    }
00909    ast_mutex_unlock(&p->lock);
00910 
00911    /* Only register a device state change if the agent is still logged in */
00912    if (!p->loginstart) {
00913       p->loginchan[0] = '\0';
00914       p->logincallerid[0] = '\0';
00915       if (persistent_agents)
00916          dump_agents();
00917    } else {
00918       ast_device_state_changed("Agent/%s", p->agent);
00919    }
00920 
00921    if (p->pending) {
00922       AST_LIST_LOCK(&agents);
00923       AST_LIST_REMOVE(&agents, p, list);
00924       AST_LIST_UNLOCK(&agents);
00925    }
00926    if (p->abouttograb) {
00927       /* Let the "about to grab" thread know this isn't valid anymore, and let it
00928          kill it later */
00929       p->abouttograb = 0;
00930    } else if (p->dead) {
00931       ast_mutex_destroy(&p->lock);
00932       ast_mutex_destroy(&p->app_lock);
00933       free(p);
00934    } else {
00935       if (p->chan) {
00936          /* Not dead -- check availability now */
00937          ast_mutex_lock(&p->lock);
00938          /* Store last disconnect time */
00939          p->lastdisc = ast_tvadd(ast_tvnow(), ast_samp2tv(p->wrapuptime, 1000));
00940          ast_mutex_unlock(&p->lock);
00941       }
00942       /* Release ownership of the agent to other threads (presumably running the login app). */
00943       if (ast_strlen_zero(p->loginchan))
00944          ast_mutex_unlock(&p->app_lock);
00945    }
00946    return 0;
00947 }
00948 
00949 static int agent_cont_sleep( void *data )
00950 {
00951    struct agent_pvt *p;
00952    int res;
00953 
00954    p = (struct agent_pvt *)data;
00955 
00956    ast_mutex_lock(&p->lock);
00957    res = p->app_sleep_cond;
00958    if (p->lastdisc.tv_sec) {
00959       if (ast_tvdiff_ms(ast_tvnow(), p->lastdisc) > 0) 
00960          res = 1;
00961    }
00962    ast_mutex_unlock(&p->lock);
00963 
00964    if(option_debug > 4 && !res )
00965       ast_log(LOG_DEBUG, "agent_cont_sleep() returning %d\n", res );
00966 
00967    return res;
00968 }
00969 
00970 static int agent_ack_sleep(void *data)
00971 {
00972    struct agent_pvt *p;
00973    int res=0;
00974    int to = 1000;
00975    struct ast_frame *f;
00976 
00977    /* Wait a second and look for something */
00978 
00979    p = (struct agent_pvt *) data;
00980    if (!p->chan) 
00981       return -1;
00982 
00983    for(;;) {
00984       to = ast_waitfor(p->chan, to);
00985       if (to < 0) 
00986          return -1;
00987       if (!to) 
00988          return 0;
00989       f = ast_read(p->chan);
00990       if (!f) 
00991          return -1;
00992       if (f->frametype == AST_FRAME_DTMF)
00993          res = f->subclass;
00994       else
00995          res = 0;
00996       ast_frfree(f);
00997       ast_mutex_lock(&p->lock);
00998       if (!p->app_sleep_cond) {
00999          ast_mutex_unlock(&p->lock);
01000          return 0;
01001       } else if (res == '#') {
01002          ast_mutex_unlock(&p->lock);
01003          return 1;
01004       }
01005       ast_mutex_unlock(&p->lock);
01006       res = 0;
01007    }
01008    return res;
01009 }
01010 
01011 static struct ast_channel *agent_bridgedchannel(struct ast_channel *chan, struct ast_channel *bridge)
01012 {
01013    struct agent_pvt *p = bridge->tech_pvt;
01014    struct ast_channel *ret = NULL;
01015 
01016    if (p) {
01017       if (chan == p->chan)
01018          ret = bridge->_bridge;
01019       else if (chan == bridge->_bridge)
01020          ret = p->chan;
01021    }
01022 
01023    if (option_debug)
01024       ast_log(LOG_DEBUG, "Asked for bridged channel on '%s'/'%s', returning '%s'\n", chan->name, bridge->name, ret ? ret->name : "<none>");
01025    return ret;
01026 }
01027 
01028 /*! \brief Create new agent channel */
01029 static struct ast_channel *agent_new(struct agent_pvt *p, int state)
01030 {
01031    struct ast_channel *tmp;
01032 #if 0
01033    if (!p->chan) {
01034       ast_log(LOG_WARNING, "No channel? :(\n");
01035       return NULL;
01036    }
01037 #endif   
01038    if (p->pending)
01039       tmp = ast_channel_alloc(0, state, 0, 0, "", p->chan ? p->chan->exten:"", p->chan ? p->chan->context:"", 0, "Agent/P%s-%d", p->agent, (int) ast_random() & 0xffff);
01040    else
01041       tmp = ast_channel_alloc(0, state, 0, 0, "", p->chan ? p->chan->exten:"", p->chan ? p->chan->context:"", 0, "Agent/%s", p->agent);
01042    if (!tmp) {
01043       ast_log(LOG_WARNING, "Unable to allocate agent channel structure\n");
01044       return NULL;
01045    }
01046 
01047    tmp->tech = &agent_tech;
01048    if (p->chan) {
01049       tmp->nativeformats = p->chan->nativeformats;
01050       tmp->writeformat = p->chan->writeformat;
01051       tmp->rawwriteformat = p->chan->writeformat;
01052       tmp->readformat = p->chan->readformat;
01053       tmp->rawreadformat = p->chan->readformat;
01054       ast_string_field_set(tmp, language, p->chan->language);
01055       ast_copy_string(tmp->context, p->chan->context, sizeof(tmp->context));
01056       ast_copy_string(tmp->exten, p->chan->exten, sizeof(tmp->exten));
01057       /* XXX Is this really all we copy form the originating channel?? */
01058    } else {
01059       tmp->nativeformats = AST_FORMAT_SLINEAR;
01060       tmp->writeformat = AST_FORMAT_SLINEAR;
01061       tmp->rawwriteformat = AST_FORMAT_SLINEAR;
01062       tmp->readformat = AST_FORMAT_SLINEAR;
01063       tmp->rawreadformat = AST_FORMAT_SLINEAR;
01064    }
01065    /* Safe, agentlock already held */
01066    tmp->tech_pvt = p;
01067    p->owner = tmp;
01068    /* XXX: this needs fixing */
01069 #if 0
01070    ast_atomic_fetchadd_int(&__mod_desc->usecnt, +1);
01071 #endif
01072    ast_update_use_count();
01073    tmp->priority = 1;
01074    /* Wake up and wait for other applications (by definition the login app)
01075     * to release this channel). Takes ownership of the agent channel
01076     * to this thread only.
01077     * For signalling the other thread, ast_queue_frame is used until we
01078     * can safely use signals for this purpose. The pselect() needs to be
01079     * implemented in the kernel for this.
01080     */
01081    p->app_sleep_cond = 0;
01082    if(ast_strlen_zero(p->loginchan) && ast_mutex_trylock(&p->app_lock)) {
01083       if (p->chan) {
01084          ast_queue_frame(p->chan, &ast_null_frame);
01085          ast_mutex_unlock(&p->lock);   /* For other thread to read the condition. */
01086          ast_mutex_lock(&p->app_lock);
01087          ast_mutex_lock(&p->lock);
01088       } else {
01089          ast_log(LOG_WARNING, "Agent disconnected while we were connecting the call\n");
01090          p->owner = NULL;
01091          tmp->tech_pvt = NULL;
01092          p->app_sleep_cond = 1;
01093          ast_channel_free( tmp );
01094          ast_mutex_unlock(&p->lock);   /* For other thread to read the condition. */
01095          ast_mutex_unlock(&p->app_lock);
01096          return NULL;
01097       }
01098    } else if (!ast_strlen_zero(p->loginchan)) {
01099       if (p->chan)
01100          ast_queue_frame(p->chan, &ast_null_frame);
01101       if (!p->chan) {
01102          ast_log(LOG_WARNING, "Agent disconnected while we were connecting the call\n");
01103          p->owner = NULL;
01104          tmp->tech_pvt = NULL;
01105          p->app_sleep_cond = 1;
01106          ast_channel_free( tmp );
01107          ast_mutex_unlock(&p->lock);     /* For other thread to read the condition. */
01108          return NULL;
01109       }  
01110    } 
01111    if (p->chan)
01112       ast_indicate(p->chan, AST_CONTROL_UNHOLD);
01113    p->owning_app = pthread_self();
01114    /* After the above step, there should not be any blockers. */
01115    if (p->chan) {
01116       if (ast_test_flag(p->chan, AST_FLAG_BLOCKING)) {
01117          ast_log( LOG_ERROR, "A blocker exists after agent channel ownership acquired\n" );
01118          ast_assert(ast_test_flag(p->chan, AST_FLAG_BLOCKING) == 0);
01119       }
01120    }
01121    return tmp;
01122 }
01123 
01124 
01125 /*!
01126  * Read configuration data. The file named agents.conf.
01127  *
01128  * \returns Always 0, or so it seems.
01129  */
01130 static int read_agent_config(void)
01131 {
01132    struct ast_config *cfg;
01133    struct ast_config *ucfg;
01134    struct ast_variable *v;
01135    struct agent_pvt *p;
01136    const char *general_val;
01137    const char *catname;
01138    const char *hasagent;
01139    int genhasagent;
01140 
01141    group = 0;
01142    autologoff = 0;
01143    wrapuptime = 0;
01144    ackcall = 0;
01145    endcall = 1;
01146    cfg = ast_config_load(config);
01147    if (!cfg) {
01148       ast_log(LOG_NOTICE, "No agent configuration found -- agent support disabled\n");
01149       return 0;
01150    }
01151    AST_LIST_LOCK(&agents);
01152    AST_LIST_TRAVERSE(&agents, p, list) {
01153       p->dead = 1;
01154    }
01155    strcpy(moh, "default");
01156    /* set the default recording values */
01157    recordagentcalls = 0;
01158    strcpy(recordformat, "wav");
01159    strcpy(recordformatext, "wav");
01160    urlprefix[0] = '\0';
01161    savecallsin[0] = '\0';
01162 
01163    /* Read in [general] section for persistence */
01164    if ((general_val = ast_variable_retrieve(cfg, "general", "persistentagents")))
01165       persistent_agents = ast_true(general_val);
01166    multiplelogin = ast_true(ast_variable_retrieve(cfg, "general", "multiplelogin"));
01167 
01168    /* Read in the [agents] section */
01169    v = ast_variable_browse(cfg, "agents");
01170    while(v) {
01171       /* Create the interface list */
01172       if (!strcasecmp(v->name, "agent")) {
01173          add_agent(v->value, 0);
01174       } else if (!strcasecmp(v->name, "group")) {
01175          group = ast_get_group(v->value);
01176       } else if (!strcasecmp(v->name, "autologoff")) {
01177          autologoff = atoi(v->value);
01178          if (autologoff < 0)
01179             autologoff = 0;
01180       } else if (!strcasecmp(v->name, "ackcall")) {
01181          if (!strcasecmp(v->value, "always"))
01182             ackcall = 2;
01183          else if (ast_true(v->value))
01184             ackcall = 1;
01185          else
01186             ackcall = 0;
01187       } else if (!strcasecmp(v->name, "endcall")) {
01188          endcall = ast_true(v->value);
01189       } else if (!strcasecmp(v->name, "wrapuptime")) {
01190          wrapuptime = atoi(v->value);
01191          if (wrapuptime < 0)
01192             wrapuptime = 0;
01193       } else if (!strcasecmp(v->name, "maxlogintries") && !ast_strlen_zero(v->value)) {
01194          maxlogintries = atoi(v->value);
01195          if (maxlogintries < 0)
01196             maxlogintries = 0;
01197       } else if (!strcasecmp(v->name, "goodbye") && !ast_strlen_zero(v->value)) {
01198          strcpy(agentgoodbye,v->value);
01199       } else if (!strcasecmp(v->name, "musiconhold")) {
01200          ast_copy_string(moh, v->value, sizeof(moh));
01201       } else if (!strcasecmp(v->name, "updatecdr")) {
01202          if (ast_true(v->value))
01203             updatecdr = 1;
01204          else
01205             updatecdr = 0;
01206       } else if (!strcasecmp(v->name, "autologoffunavail")) {
01207          if (ast_true(v->value))
01208             autologoffunavail = 1;
01209          else
01210             autologoffunavail = 0;
01211       } else if (!strcasecmp(v->name, "recordagentcalls")) {
01212          recordagentcalls = ast_true(v->value);
01213       } else if (!strcasecmp(v->name, "recordformat")) {
01214          ast_copy_string(recordformat, v->value, sizeof(recordformat));
01215          if (!strcasecmp(v->value, "wav49"))
01216             strcpy(recordformatext, "WAV");
01217          else
01218             ast_copy_string(recordformatext, v->value, sizeof(recordformatext));
01219       } else if (!strcasecmp(v->name, "urlprefix")) {
01220          ast_copy_string(urlprefix, v->value, sizeof(urlprefix));
01221          if (urlprefix[strlen(urlprefix) - 1] != '/')
01222             strncat(urlprefix, "/", sizeof(urlprefix) - strlen(urlprefix) - 1);
01223       } else if (!strcasecmp(v->name, "savecallsin")) {
01224          if (v->value[0] == '/')
01225             ast_copy_string(savecallsin, v->value, sizeof(savecallsin));
01226          else
01227             snprintf(savecallsin, sizeof(savecallsin) - 2, "/%s", v->value);
01228          if (savecallsin[strlen(savecallsin) - 1] != '/')
01229             strncat(savecallsin, "/", sizeof(savecallsin) - strlen(savecallsin) - 1);
01230       } else if (!strcasecmp(v->name, "custom_beep")) {
01231          ast_copy_string(beep, v->value, sizeof(beep));
01232       }
01233       v = v->next;
01234    }
01235    if ((ucfg = ast_config_load("users.conf"))) {
01236       genhasagent = ast_true(ast_variable_retrieve(ucfg, "general", "hasagent"));
01237       catname = ast_category_browse(ucfg, NULL);
01238       while(catname) {
01239          if (strcasecmp(catname, "general")) {
01240             hasagent = ast_variable_retrieve(ucfg, catname, "hasagent");
01241             if (ast_true(hasagent) || (!hasagent && genhasagent)) {
01242                char tmp[256];
01243                const char *fullname = ast_variable_retrieve(ucfg, catname, "fullname");
01244                const char *secret = ast_variable_retrieve(ucfg, catname, "secret");
01245                if (!fullname)
01246                   fullname = "";
01247                if (!secret)
01248                   secret = "";
01249                snprintf(tmp, sizeof(tmp), "%s,%s,%s", catname, secret,fullname);
01250                add_agent(tmp, 0);
01251             }
01252          }
01253          catname = ast_category_browse(ucfg, catname);
01254       }
01255       ast_config_destroy(ucfg);
01256    }
01257    AST_LIST_TRAVERSE_SAFE_BEGIN(&agents, p, list) {
01258       if (p->dead) {
01259          AST_LIST_REMOVE_CURRENT(&agents, list);
01260          /* Destroy if  appropriate */
01261          if (!p->owner) {
01262             if (!p->chan) {
01263                ast_mutex_destroy(&p->lock);
01264                ast_mutex_destroy(&p->app_lock);
01265                free(p);
01266             } else {
01267                /* Cause them to hang up */
01268                ast_softhangup(p->chan, AST_SOFTHANGUP_EXPLICIT);
01269             }
01270          }
01271       }
01272    }
01273    AST_LIST_TRAVERSE_SAFE_END
01274    AST_LIST_UNLOCK(&agents);
01275    ast_config_destroy(cfg);
01276    return 1;
01277 }
01278 
01279 static int check_availability(struct agent_pvt *newlyavailable, int needlock)
01280 {
01281    struct ast_channel *chan=NULL, *parent=NULL;
01282    struct agent_pvt *p;
01283    int res;
01284 
01285    if (option_debug)
01286       ast_log(LOG_DEBUG, "Checking availability of '%s'\n", newlyavailable->agent);
01287    if (needlock)
01288       AST_LIST_LOCK(&agents);
01289    AST_LIST_TRAVERSE(&agents, p, list) {
01290       if (p == newlyavailable) {
01291          continue;
01292       }
01293       ast_mutex_lock(&p->lock);
01294       if (!p->abouttograb && p->pending && ((p->group && (newlyavailable->group & p->group)) || !strcmp(p->agent, newlyavailable->agent))) {
01295          if (option_debug)
01296             ast_log(LOG_DEBUG, "Call '%s' looks like a winner for agent '%s'\n", p->owner->name, newlyavailable->agent);
01297          /* We found a pending call, time to merge */
01298          chan = agent_new(newlyavailable, AST_STATE_DOWN);
01299          parent = p->owner;
01300          p->abouttograb = 1;
01301          ast_mutex_unlock(&p->lock);
01302          break;
01303       }
01304       ast_mutex_unlock(&p->lock);
01305    }
01306    if (needlock)
01307       AST_LIST_UNLOCK(&agents);
01308    if (parent && chan)  {
01309       if (newlyavailable->ackcall > 1) {
01310          /* Don't do beep here */
01311          res = 0;
01312       } else {
01313          if (option_debug > 2)
01314             ast_log( LOG_DEBUG, "Playing beep, lang '%s'\n", newlyavailable->chan->language);
01315          res = ast_streamfile(newlyavailable->chan, beep, newlyavailable->chan->language);
01316          if (option_debug > 2)
01317             ast_log( LOG_DEBUG, "Played beep, result '%d'\n", res);
01318          if (!res) {
01319             res = ast_waitstream(newlyavailable->chan, "");
01320             ast_log( LOG_DEBUG, "Waited for stream, result '%d'\n", res);
01321          }
01322       }
01323       if (!res) {
01324          /* Note -- parent may have disappeared */
01325          if (p->abouttograb) {
01326             newlyavailable->acknowledged = 1;
01327             /* Safe -- agent lock already held */
01328             ast_setstate(parent, AST_STATE_UP);
01329             ast_setstate(chan, AST_STATE_UP);
01330             ast_copy_string(parent->context, chan->context, sizeof(parent->context));
01331             /* Go ahead and mark the channel as a zombie so that masquerade will
01332                destroy it for us, and we need not call ast_hangup */
01333             ast_mutex_lock(&parent->lock);
01334             ast_set_flag(chan, AST_FLAG_ZOMBIE);
01335             ast_channel_masquerade(parent, chan);
01336             ast_mutex_unlock(&parent->lock);
01337             p->abouttograb = 0;
01338          } else {
01339             if (option_debug)
01340                ast_log(LOG_DEBUG, "Sneaky, parent disappeared in the mean time...\n");
01341             agent_cleanup(newlyavailable);
01342          }
01343       } else {
01344          if (option_debug)
01345             ast_log(LOG_DEBUG, "Ugh...  Agent hung up at exactly the wrong time\n");
01346          agent_cleanup(newlyavailable);
01347       }
01348    }
01349    return 0;
01350 }
01351 
01352 static int check_beep(struct agent_pvt *newlyavailable, int needlock)
01353 {
01354    struct agent_pvt *p;
01355    int res=0;
01356 
01357    ast_log(LOG_DEBUG, "Checking beep availability of '%s'\n", newlyavailable->agent);
01358    if (needlock)
01359       AST_LIST_LOCK(&agents);
01360    AST_LIST_TRAVERSE(&agents, p, list) {
01361       if (p == newlyavailable) {
01362          continue;
01363       }
01364       ast_mutex_lock(&p->lock);
01365       if (!p->abouttograb && p->pending && ((p->group && (newlyavailable->group & p->group)) || !strcmp(p->agent, newlyavailable->agent))) {
01366          if (option_debug)
01367             ast_log(LOG_DEBUG, "Call '%s' looks like a would-be winner for agent '%s'\n", p->owner->name, newlyavailable->agent);
01368          ast_mutex_unlock(&p->lock);
01369          break;
01370       }
01371       ast_mutex_unlock(&p->lock);
01372    }
01373    if (needlock)
01374       AST_LIST_UNLOCK(&agents);
01375    if (p) {
01376       ast_mutex_unlock(&newlyavailable->lock);
01377       if (option_debug > 2)
01378          ast_log( LOG_DEBUG, "Playing beep, lang '%s'\n", newlyavailable->chan->language);
01379       res = ast_streamfile(newlyavailable->chan, beep, newlyavailable->chan->language);
01380       if (option_debug > 2)
01381          ast_log( LOG_DEBUG, "Played beep, result '%d'\n", res);
01382       if (!res) {
01383          res = ast_waitstream(newlyavailable->chan, "");
01384          if (option_debug)
01385             ast_log( LOG_DEBUG, "Waited for stream, result '%d'\n", res);
01386       }
01387       ast_mutex_lock(&newlyavailable->lock);
01388    }
01389    return res;
01390 }
01391 
01392 /* return 1 if multiple login is fine, 0 if it is not and we find a match, -1 if multiplelogin is not allowed and we don't find a match. */
01393 static int allow_multiple_login(char *chan, char *context)
01394 {
01395    struct agent_pvt *p;
01396    char loginchan[80];
01397 
01398    if(multiplelogin)
01399       return 1;
01400    if(!chan) 
01401       return 0;
01402 
01403    snprintf(loginchan, sizeof(loginchan), "%s@%s", chan, S_OR(context, "default"));
01404    
01405    AST_LIST_TRAVERSE(&agents, p, list) {
01406       if(!strcasecmp(chan, p->loginchan))
01407          return 0;
01408    }
01409    return -1;
01410 }
01411 
01412 /*! \brief Part of the Asterisk PBX interface */
01413 static struct ast_channel *agent_request(const char *type, int format, void *data, int *cause)
01414 {
01415    struct agent_pvt *p;
01416    struct ast_channel *chan = NULL;
01417    char *s;
01418    ast_group_t groupmatch;
01419    int groupoff;
01420    int waitforagent=0;
01421    int hasagent = 0;
01422    struct timeval tv;
01423 
01424    s = data;
01425    if ((s[0] == '@') && (sscanf(s + 1, "%d", &groupoff) == 1)) {
01426       groupmatch = (1 << groupoff);
01427    } else if ((s[0] == ':') && (sscanf(s + 1, "%d", &groupoff) == 1)) {
01428       groupmatch = (1 << groupoff);
01429       waitforagent = 1;
01430    } else 
01431       groupmatch = 0;
01432 
01433    /* Check actual logged in agents first */
01434    AST_LIST_LOCK(&agents);
01435    AST_LIST_TRAVERSE(&agents, p, list) {
01436       ast_mutex_lock(&p->lock);
01437       if (!p->pending && ((groupmatch && (p->group & groupmatch)) || !strcmp(data, p->agent)) &&
01438           ast_strlen_zero(p->loginchan)) {
01439          if (p->chan)
01440             hasagent++;
01441          tv = ast_tvnow();
01442          if (!p->lastdisc.tv_sec || (tv.tv_sec >= p->lastdisc.tv_sec)) {
01443             p->lastdisc = ast_tv(0, 0);
01444             /* Agent must be registered, but not have any active call, and not be in a waiting state */
01445             if (!p->owner && p->chan) {
01446                /* Fixed agent */
01447                chan = agent_new(p, AST_STATE_DOWN);
01448             }
01449             if (chan) {
01450                ast_mutex_unlock(&p->lock);
01451                break;
01452             }
01453          }
01454       }
01455       ast_mutex_unlock(&p->lock);
01456    }
01457    if (!p) {
01458       AST_LIST_TRAVERSE(&agents, p, list) {
01459          ast_mutex_lock(&p->lock);
01460          if (!p->pending && ((groupmatch && (p->group & groupmatch)) || !strcmp(data, p->agent))) {
01461             if (p->chan || !ast_strlen_zero(p->loginchan))
01462                hasagent++;
01463             tv = ast_tvnow();
01464 #if 0
01465             ast_log(LOG_NOTICE, "Time now: %ld, Time of lastdisc: %ld\n", tv.tv_sec, p->lastdisc.tv_sec);
01466 #endif
01467             if (!p->lastdisc.tv_sec || (tv.tv_sec >= p->lastdisc.tv_sec)) {
01468                p->lastdisc = ast_tv(0, 0);
01469                /* Agent must be registered, but not have any active call, and not be in a waiting state */
01470                if (!p->owner && p->chan) {
01471                   /* Could still get a fixed agent */
01472                   chan = agent_new(p, AST_STATE_DOWN);
01473                } else if (!p->owner && !ast_strlen_zero(p->loginchan)) {
01474                   /* Adjustable agent */
01475                   p->chan = ast_request("Local", format, p->loginchan, cause);
01476                   if (p->chan)
01477                      chan = agent_new(p, AST_STATE_DOWN);
01478                }
01479                if (chan) {
01480                   ast_mutex_unlock(&p->lock);
01481                   break;
01482                }
01483             }
01484          }
01485          ast_mutex_unlock(&p->lock);
01486       }
01487    }
01488 
01489    if (!chan && waitforagent) {
01490       /* No agent available -- but we're requesting to wait for one.
01491          Allocate a place holder */
01492       if (hasagent) {
01493          if (option_debug)
01494             ast_log(LOG_DEBUG, "Creating place holder for '%s'\n", s);
01495          p = add_agent(data, 1);
01496          p->group = groupmatch;
01497          chan = agent_new(p, AST_STATE_DOWN);
01498          if (!chan) 
01499             ast_log(LOG_WARNING, "Weird...  Fix this to drop the unused pending agent\n");
01500       } else
01501          ast_log(LOG_DEBUG, "Not creating place holder for '%s' since nobody logged in\n", s);
01502    }
01503    *cause = hasagent ? AST_CAUSE_BUSY : AST_CAUSE_UNREGISTERED;
01504    AST_LIST_UNLOCK(&agents);
01505    return chan;
01506 }
01507 
01508 static force_inline int powerof(unsigned int d)
01509 {
01510    int x = ffs(d);
01511 
01512    if (x)
01513       return x - 1;
01514 
01515    return 0;
01516 }
01517 
01518 /*!
01519  * Lists agents and their status to the Manager API.
01520  * It is registered on load_module() and it gets called by the manager backend.
01521  * \param s
01522  * \param m
01523  * \returns 
01524  * \sa action_agent_logoff(), action_agent_callback_login(), load_module().
01525  */
01526 static int action_agents(struct mansession *s, const struct message *m)
01527 {
01528    const char *id = astman_get_header(m,"ActionID");
01529    char idText[256] = "";
01530    char chanbuf[256];
01531    struct agent_pvt *p;
01532    char *username = NULL;
01533    char *loginChan = NULL;
01534    char *talkingtoChan = NULL;
01535    char *status = NULL;
01536 
01537    if (!ast_strlen_zero(id))
01538       snprintf(idText, sizeof(idText) ,"ActionID: %s\r\n", id);
01539    astman_send_ack(s, m, "Agents will follow");
01540    AST_LIST_LOCK(&agents);
01541    AST_LIST_TRAVERSE(&agents, p, list) {
01542          ast_mutex_lock(&p->lock);
01543 
01544       /* Status Values:
01545          AGENT_LOGGEDOFF - Agent isn't logged in
01546          AGENT_IDLE      - Agent is logged in, and waiting for call
01547          AGENT_ONCALL    - Agent is logged in, and on a call
01548          AGENT_UNKNOWN   - Don't know anything about agent. Shouldn't ever get this. */
01549 
01550       username = S_OR(p->name, "None");
01551 
01552       /* Set a default status. It 'should' get changed. */
01553       status = "AGENT_UNKNOWN";
01554 
01555       if (!ast_strlen_zero(p->loginchan) && !p->chan) {
01556          loginChan = p->loginchan;
01557          talkingtoChan = "n/a";
01558          status = "AGENT_IDLE";
01559          if (p->acknowledged) {
01560             snprintf(chanbuf, sizeof(chanbuf), " %s (Confirmed)", p->loginchan);
01561             loginChan = chanbuf;
01562          }
01563       } else if (p->chan) {
01564          loginChan = ast_strdupa(p->chan->name);
01565          if (p->owner && p->owner->_bridge) {
01566             if (ast_bridged_channel(p->owner)) {
01567                talkingtoChan = ast_strdupa(S_OR(ast_bridged_channel(p->owner)->cid.cid_num, ""));
01568             } else {
01569                talkingtoChan = "n/a";
01570             }
01571                status = "AGENT_ONCALL";
01572          } else {
01573                talkingtoChan = "n/a";
01574                status = "AGENT_IDLE";
01575          }
01576       } else {
01577          loginChan = "n/a";
01578          talkingtoChan = "n/a";
01579          status = "AGENT_LOGGEDOFF";
01580       }
01581 
01582       astman_append(s, "Event: Agents\r\n"
01583          "Agent: %s\r\n"
01584          "Name: %s\r\n"
01585          "Status: %s\r\n"
01586          "LoggedInChan: %s\r\n"
01587          "LoggedInTime: %d\r\n"
01588          "TalkingTo: %s\r\n"
01589          "%s"
01590          "\r\n",
01591          p->agent, username, status, loginChan, (int)p->loginstart, talkingtoChan, idText);
01592       ast_mutex_unlock(&p->lock);
01593    }
01594    AST_LIST_UNLOCK(&agents);
01595    astman_append(s, "Event: AgentsComplete\r\n"
01596       "%s"
01597       "\r\n",idText);
01598    return 0;
01599 }
01600 
01601 static void agent_logoff_maintenance(struct agent_pvt *p, char *loginchan, long logintime, const char *uniqueid, char *logcommand)
01602 {
01603    char *tmp = NULL;
01604    char agent[AST_MAX_AGENT];
01605 
01606    if (!ast_strlen_zero(logcommand))
01607       tmp = logcommand;
01608    else
01609       tmp = ast_strdupa("");
01610 
01611    snprintf(agent, sizeof(agent), "Agent/%s", p->agent);
01612 
01613    if (!ast_strlen_zero(uniqueid)) {
01614       manager_event(EVENT_FLAG_AGENT, "Agentcallbacklogoff",
01615             "Agent: %s\r\n"
01616             "Reason: %s\r\n"
01617             "Loginchan: %s\r\n"
01618             "Logintime: %ld\r\n"
01619             "Uniqueid: %s\r\n", 
01620             p->agent, tmp, loginchan, logintime, uniqueid);
01621    } else {
01622       manager_event(EVENT_FLAG_AGENT, "Agentcallbacklogoff",
01623             "Agent: %s\r\n"
01624             "Reason: %s\r\n"
01625             "Loginchan: %s\r\n"
01626             "Logintime: %ld\r\n",
01627             p->agent, tmp, loginchan, logintime);
01628    }
01629 
01630    ast_queue_log("NONE", ast_strlen_zero(uniqueid) ? "NONE" : uniqueid, agent, "AGENTCALLBACKLOGOFF", "%s|%ld|%s", loginchan, logintime, tmp);
01631    set_agentbycallerid(p->logincallerid, NULL);
01632    p->loginchan[0] ='\0';
01633    p->logincallerid[0] = '\0';
01634    p->inherited_devicestate = -1;
01635    ast_device_state_changed("Agent/%s", p->agent);
01636    if (persistent_agents)
01637       dump_agents(); 
01638 
01639 }
01640 
01641 static int agent_logoff(const char *agent, int soft)
01642 {
01643    struct agent_pvt *p;
01644    long logintime;
01645    int ret = -1; /* Return -1 if no agent if found */
01646 
01647    AST_LIST_LOCK(&agents);
01648    AST_LIST_TRAVERSE(&agents, p, list) {
01649       if (!strcasecmp(p->agent, agent)) {
01650          ret = 0;
01651          if (p->owner || p->chan) {
01652             if (!soft) {
01653                ast_mutex_lock(&p->lock);
01654 
01655                while (p->owner && ast_channel_trylock(p->owner)) {
01656                   DEADLOCK_AVOIDANCE(&p->lock);
01657                }
01658                if (p->owner) {
01659                   ast_softhangup(p->owner, AST_SOFTHANGUP_EXPLICIT);
01660                   ast_channel_unlock(p->owner);
01661                }
01662 
01663                while (p->chan && ast_channel_trylock(p->chan)) {
01664                   DEADLOCK_AVOIDANCE(&p->lock);
01665                }
01666                if (p->chan) {
01667                   ast_softhangup(p->chan, AST_SOFTHANGUP_EXPLICIT);
01668                   ast_channel_unlock(p->chan);
01669                }
01670 
01671                ast_mutex_unlock(&p->lock);
01672             } else
01673                p->deferlogoff = 1;
01674          } else {
01675             logintime = time(NULL) - p->loginstart;
01676             p->loginstart = 0;
01677             agent_logoff_maintenance(p, p->loginchan, logintime, NULL, "CommandLogoff");
01678          }
01679          break;
01680       }
01681    }
01682    AST_LIST_UNLOCK(&agents);
01683 
01684    return ret;
01685 }
01686 
01687 static int agent_logoff_cmd(int fd, int argc, char **argv)
01688 {
01689    int ret;
01690    char *agent;
01691 
01692    if (argc < 3 || argc > 4)
01693       return RESULT_SHOWUSAGE;
01694    if (argc == 4 && strcasecmp(argv[3], "soft"))
01695       return RESULT_SHOWUSAGE;
01696 
01697    agent = argv[2] + 6;
01698    ret = agent_logoff(agent, argc == 4);
01699    if (ret == 0)
01700       ast_cli(fd, "Logging out %s\n", agent);
01701 
01702    return RESULT_SUCCESS;
01703 }
01704 
01705 /*!
01706  * Sets an agent as no longer logged in in the Manager API.
01707  * It is registered on load_module() and it gets called by the manager backend.
01708  * \param s
01709  * \param m
01710  * \returns 
01711  * \sa action_agents(), action_agent_callback_login(), load_module().
01712  */
01713 static int action_agent_logoff(struct mansession *s, const struct message *m)
01714 {
01715    const char *agent = astman_get_header(m, "Agent");
01716    const char *soft_s = astman_get_header(m, "Soft"); /* "true" is don't hangup */
01717    int soft;
01718    int ret; /* return value of agent_logoff */
01719 
01720    if (ast_strlen_zero(agent)) {
01721       astman_send_error(s, m, "No agent specified");
01722       return 0;
01723    }
01724 
01725    soft = ast_true(soft_s) ? 1 : 0;
01726    ret = agent_logoff(agent, soft);
01727    if (ret == 0)
01728       astman_send_ack(s, m, "Agent logged out");
01729    else
01730       astman_send_error(s, m, "No such agent");
01731 
01732    return 0;
01733 }
01734 
01735 static char *complete_agent_logoff_cmd(const char *line, const char *word, int pos, int state)
01736 {
01737    char *ret = NULL;
01738 
01739    if (pos == 2) {
01740       struct agent_pvt *p;
01741       char name[AST_MAX_AGENT];
01742       int which = 0, len = strlen(word);
01743 
01744       AST_LIST_LOCK(&agents);
01745       AST_LIST_TRAVERSE(&agents, p, list) {
01746          snprintf(name, sizeof(name), "Agent/%s", p->agent);
01747          if (!strncasecmp(word, name, len) && ++which > state) {
01748             ret = ast_strdup(name);
01749             break;
01750          }
01751       }
01752       AST_LIST_UNLOCK(&agents);
01753    } else if (pos == 3 && state == 0) 
01754       return ast_strdup("soft");
01755    
01756    return ret;
01757 }
01758 
01759 /*!
01760  * Show agents in cli.
01761  */
01762 static int agents_show(int fd, int argc, char **argv)
01763 {
01764    struct agent_pvt *p;
01765    char username[AST_MAX_BUF];
01766    char location[AST_MAX_BUF] = "";
01767    char talkingto[AST_MAX_BUF] = "";
01768    char moh[AST_MAX_BUF];
01769    int count_agents = 0;      /*!< Number of agents configured */
01770    int online_agents = 0;     /*!< Number of online agents */
01771    int offline_agents = 0;    /*!< Number of offline agents */
01772    if (argc != 2)
01773       return RESULT_SHOWUSAGE;
01774    AST_LIST_LOCK(&agents);
01775    AST_LIST_TRAVERSE(&agents, p, list) {
01776       ast_mutex_lock(&p->lock);
01777       if (p->pending) {
01778          if (p->group)
01779             ast_cli(fd, "-- Pending call to group %d\n", powerof(p->group));
01780          else
01781             ast_cli(fd, "-- Pending call to agent %s\n", p->agent);
01782       } else {
01783          if (!ast_strlen_zero(p->name))
01784             snprintf(username, sizeof(username), "(%s) ", p->name);
01785          else
01786             username[0] = '\0';
01787          if (p->chan) {
01788             snprintf(location, sizeof(location), "logged in on %s", p->chan->name);
01789             if (p->owner && ast_bridged_channel(p->owner))
01790                snprintf(talkingto, sizeof(talkingto), " talking to %s", ast_bridged_channel(p->owner)->name);
01791              else 
01792                strcpy(talkingto, " is idle");
01793             online_agents++;
01794          } else if (!ast_strlen_zero(p->loginchan)) {
01795             if (ast_tvdiff_ms(ast_tvnow(), p->lastdisc) > 0 || !(p->lastdisc.tv_sec)) 
01796                snprintf(location, sizeof(location) - 20, "available at '%s'", p->loginchan);
01797             else 
01798                snprintf(location, sizeof(location) - 20, "wrapping up at '%s'", p->loginchan);
01799             talkingto[0] = '\0';
01800             online_agents++;
01801             if (p->acknowledged)
01802                strncat(location, " (Confirmed)", sizeof(location) - strlen(location) - 1);
01803          } else {
01804             strcpy(location, "not logged in");
01805             talkingto[0] = '\0';
01806             offline_agents++;
01807          }
01808          if (!ast_strlen_zero(p->moh))
01809             snprintf(moh, sizeof(moh), " (musiconhold is '%s')", p->moh);
01810          ast_cli(fd, "%-12.12s %s%s%s%s\n", p->agent, 
01811             username, location, talkingto, moh);
01812          count_agents++;
01813       }
01814       ast_mutex_unlock(&p->lock);
01815    }
01816    AST_LIST_UNLOCK(&agents);
01817    if ( !count_agents ) 
01818       ast_cli(fd, "No Agents are configured in %s\n",config);
01819    else 
01820       ast_cli(fd, "%d agents configured [%d online , %d offline]\n",count_agents, online_agents, offline_agents);
01821    ast_cli(fd, "\n");
01822                    
01823    return RESULT_SUCCESS;
01824 }
01825 
01826 
01827 static int agents_show_online(int fd, int argc, char **argv)
01828 {
01829    struct agent_pvt *p;
01830    char username[AST_MAX_BUF];
01831    char location[AST_MAX_BUF] = "";
01832    char talkingto[AST_MAX_BUF] = "";
01833    char moh[AST_MAX_BUF];
01834    int count_agents = 0;           /* Number of agents configured */
01835    int online_agents = 0;          /* Number of online agents */
01836    int agent_status = 0;           /* 0 means offline, 1 means online */
01837    if (argc != 3)
01838       return RESULT_SHOWUSAGE;
01839    AST_LIST_LOCK(&agents);
01840    AST_LIST_TRAVERSE(&agents, p, list) {
01841       agent_status = 0;       /* reset it to offline */
01842       ast_mutex_lock(&p->lock);
01843       if (!ast_strlen_zero(p->name))
01844          snprintf(username, sizeof(username), "(%s) ", p->name);
01845       else
01846          username[0] = '\0';
01847       if (p->chan) {
01848          snprintf(location, sizeof(location), "logged in on %s", p->chan->name);
01849          if (p->owner && ast_bridged_channel(p->owner)) 
01850             snprintf(talkingto, sizeof(talkingto), " talking to %s", ast_bridged_channel(p->owner)->name);
01851          else 
01852             strcpy(talkingto, " is idle");
01853          agent_status = 1;
01854          online_agents++;
01855       } else if (!ast_strlen_zero(p->loginchan)) {
01856          snprintf(location, sizeof(location) - 20, "available at '%s'", p->loginchan);
01857          talkingto[0] = '\0';
01858          agent_status = 1;
01859          online_agents++;
01860          if (p->acknowledged)
01861             strncat(location, " (Confirmed)", sizeof(location) - strlen(location) - 1);
01862       }
01863       if (!ast_strlen_zero(p->moh))
01864          snprintf(moh, sizeof(moh), " (musiconhold is '%s')", p->moh);
01865       if (agent_status)
01866          ast_cli(fd, "%-12.12s %s%s%s%s\n", p->agent, username, location, talkingto, moh);
01867       count_agents++;
01868       ast_mutex_unlock(&p->lock);
01869    }
01870    AST_LIST_UNLOCK(&agents);
01871    if (!count_agents) 
01872       ast_cli(fd, "No Agents are configured in %s\n", config);
01873    else
01874       ast_cli(fd, "%d agents online\n", online_agents);
01875    ast_cli(fd, "\n");
01876    return RESULT_SUCCESS;
01877 }
01878 
01879 
01880 
01881 static char show_agents_usage[] = 
01882 "Usage: agent show\n"
01883 "       Provides summary information on agents.\n";
01884 
01885 static char show_agents_online_usage[] =
01886 "Usage: agent show online\n"
01887 "  Provides a list of all online agents.\n";
01888 
01889 static char agent_logoff_usage[] =
01890 "Usage: agent logoff <channel> [soft]\n"
01891 "       Sets an agent as no longer logged in.\n"
01892 "       If 'soft' is specified, do not hangup existing calls.\n";
01893 
01894 static struct ast_cli_entry cli_show_agents_deprecated = {
01895    { "show", "agents", NULL },
01896    agents_show, NULL,
01897    NULL, NULL };
01898 
01899 static struct ast_cli_entry cli_show_agents_online_deprecated = {
01900    { "show", "agents", "online" },
01901    agents_show_online, NULL,
01902    NULL, NULL };
01903 
01904 static struct ast_cli_entry cli_agents[] = {
01905    { { "agent", "show", NULL },
01906    agents_show, "Show status of agents",
01907    show_agents_usage, NULL, &cli_show_agents_deprecated },
01908 
01909    { { "agent", "show", "online" },
01910    agents_show_online, "Show all online agents",
01911    show_agents_online_usage, NULL, &cli_show_agents_online_deprecated },
01912 
01913    { { "agent", "logoff", NULL },
01914    agent_logoff_cmd, "Sets an agent offline",
01915    agent_logoff_usage, complete_agent_logoff_cmd },
01916 };
01917 
01918 /*!
01919  * \brief Log in agent application.
01920  *
01921  * \param chan
01922  * \param data
01923  * \param callbackmode non-zero for AgentCallbackLogin
01924  */
01925 static int __login_exec(struct ast_channel *chan, void *data, int callbackmode)
01926 {
01927    int res=0;
01928    int tries = 0;
01929    int max_login_tries = maxlogintries;
01930    struct agent_pvt *p;
01931    struct ast_module_user *u;
01932    int login_state = 0;
01933    char user[AST_MAX_AGENT] = "";
01934    char pass[AST_MAX_AGENT];
01935    char agent[AST_MAX_AGENT] = "";
01936    char xpass[AST_MAX_AGENT] = "";
01937    char *errmsg;
01938    char *parse;
01939    AST_DECLARE_APP_ARGS(args,
01940               AST_APP_ARG(agent_id);
01941               AST_APP_ARG(options);
01942               AST_APP_ARG(extension);
01943       );
01944    const char *tmpoptions = NULL;
01945    char *context = NULL;
01946    int play_announcement = 1;
01947    char agent_goodbye[AST_MAX_FILENAME_LEN];
01948    int update_cdr = updatecdr;
01949    char *filename = "agent-loginok";
01950    char tmpchan[AST_MAX_BUF] = "";
01951 
01952    u = ast_module_user_add(chan);
01953 
01954    parse = ast_strdupa(data);
01955 
01956    AST_STANDARD_APP_ARGS(args, parse);
01957 
01958    ast_copy_string(agent_goodbye, agentgoodbye, sizeof(agent_goodbye));
01959 
01960    ast_channel_lock(chan);
01961    /* Set Channel Specific Login Overrides */
01962    if (pbx_builtin_getvar_helper(chan, "AGENTLMAXLOGINTRIES") && strlen(pbx_builtin_getvar_helper(chan, "AGENTLMAXLOGINTRIES"))) {
01963       max_login_tries = atoi(pbx_builtin_getvar_helper(chan, "AGENTMAXLOGINTRIES"));
01964       if (max_login_tries < 0)
01965          max_login_tries = 0;
01966       tmpoptions=pbx_builtin_getvar_helper(chan, "AGENTMAXLOGINTRIES");
01967       if (option_verbose > 2)
01968          ast_verbose(VERBOSE_PREFIX_3 "Saw variable AGENTMAXLOGINTRIES=%s, setting max_login_tries to: %d on Channel '%s'.\n",tmpoptions,max_login_tries,chan->name);
01969    }
01970    if (pbx_builtin_getvar_helper(chan, "AGENTUPDATECDR") && !ast_strlen_zero(pbx_builtin_getvar_helper(chan, "AGENTUPDATECDR"))) {
01971       if (ast_true(pbx_builtin_getvar_helper(chan, "AGENTUPDATECDR")))
01972          update_cdr = 1;
01973       else
01974          update_cdr = 0;
01975       tmpoptions=pbx_builtin_getvar_helper(chan, "AGENTUPDATECDR");
01976       if (option_verbose > 2)
01977          ast_verbose(VERBOSE_PREFIX_3 "Saw variable AGENTUPDATECDR=%s, setting update_cdr to: %d on Channel '%s'.\n",tmpoptions,update_cdr,chan->name);
01978    }
01979    if (pbx_builtin_getvar_helper(chan, "AGENTGOODBYE") && !ast_strlen_zero(pbx_builtin_getvar_helper(chan, "AGENTGOODBYE"))) {
01980       strcpy(agent_goodbye, pbx_builtin_getvar_helper(chan, "AGENTGOODBYE"));
01981       tmpoptions=pbx_builtin_getvar_helper(chan, "AGENTGOODBYE");
01982       if (option_verbose > 2)
01983          ast_verbose(VERBOSE_PREFIX_3 "Saw variable AGENTGOODBYE=%s, setting agent_goodbye to: %s on Channel '%s'.\n",tmpoptions,agent_goodbye,chan->name);
01984    }
01985    ast_channel_unlock(chan);
01986    /* End Channel Specific Login Overrides */
01987    
01988    if (callbackmode && args.extension) {
01989       parse = args.extension;
01990       args.extension = strsep(&parse, "@");
01991       context = parse;
01992    }
01993 
01994    if (!ast_strlen_zero(args.options)) {
01995       if (strchr(args.options, 's')) {
01996          play_announcement = 0;
01997       }
01998    }
01999 
02000    if (chan->_state != AST_STATE_UP)
02001       res = ast_answer(chan);
02002    if (!res) {
02003       if (!ast_strlen_zero(args.agent_id))
02004          ast_copy_string(user, args.agent_id, AST_MAX_AGENT);
02005       else
02006          res = ast_app_getdata(chan, "agent-user", user, sizeof(user) - 1, 0);
02007    }
02008    while (!res && (max_login_tries==0 || tries < max_login_tries)) {
02009       tries++;
02010       /* Check for password */
02011       AST_LIST_LOCK(&agents);
02012       AST_LIST_TRAVERSE(&agents, p, list) {
02013          if (!strcmp(p->agent, user) && !p->pending)
02014             ast_copy_string(xpass, p->password, sizeof(xpass));
02015       }
02016       AST_LIST_UNLOCK(&agents);
02017       if (!res) {
02018          if (!ast_strlen_zero(xpass))
02019             res = ast_app_getdata(chan, "agent-pass", pass, sizeof(pass) - 1, 0);
02020          else
02021             pass[0] = '\0';
02022       }
02023       errmsg = "agent-incorrect";
02024 
02025 #if 0
02026       ast_log(LOG_NOTICE, "user: %s, pass: %s\n", user, pass);
02027 #endif      
02028 
02029       /* Check again for accuracy */
02030       AST_LIST_LOCK(&agents);
02031       AST_LIST_TRAVERSE(&agents, p, list) {
02032          int unlock_channel = 1;
02033          ast_channel_lock(chan);
02034          ast_mutex_lock(&p->lock);
02035          if (!strcmp(p->agent, user) &&
02036              !strcmp(p->password, pass) && !p->pending) {
02037             login_state = 1; /* Successful Login */
02038 
02039             /* Ensure we can't be gotten until we're done */
02040             gettimeofday(&p->lastdisc, NULL);
02041             p->lastdisc.tv_sec++;
02042 
02043             /* Set Channel Specific Agent Overrides */
02044             if (pbx_builtin_getvar_helper(chan, "AGENTACKCALL") && strlen(pbx_builtin_getvar_helper(chan, "AGENTACKCALL"))) {
02045                if (!strcasecmp(pbx_builtin_getvar_helper(chan, "AGENTACKCALL"), "always"))
02046                   p->ackcall = 2;
02047                else if (ast_true(pbx_builtin_getvar_helper(chan, "AGENTACKCALL")))
02048                   p->ackcall = 1;
02049                else
02050                   p->ackcall = 0;
02051                tmpoptions=pbx_builtin_getvar_helper(chan, "AGENTACKCALL");
02052                if (option_verbose > 2)
02053                   ast_verbose(VERBOSE_PREFIX_3 "Saw variable AGENTACKCALL=%s, setting ackcall to: %d for Agent '%s'.\n",tmpoptions,p->ackcall,p->agent);
02054             } else {
02055                p->ackcall = ackcall;
02056             }
02057             if (pbx_builtin_getvar_helper(chan, "AGENTAUTOLOGOFF") && strlen(pbx_builtin_getvar_helper(chan, "AGENTAUTOLOGOFF"))) {
02058                p->autologoff = atoi(pbx_builtin_getvar_helper(chan, "AGENTAUTOLOGOFF"));
02059                if (p->autologoff < 0)
02060                   p->autologoff = 0;
02061                tmpoptions=pbx_builtin_getvar_helper(chan, "AGENTAUTOLOGOFF");
02062                if (option_verbose > 2)
02063                   ast_verbose(VERBOSE_PREFIX_3 "Saw variable AGENTAUTOLOGOFF=%s, setting autologff to: %d for Agent '%s'.\n",tmpoptions,p->autologoff,p->agent);
02064             } else {
02065                p->autologoff = autologoff;
02066             }
02067             if (pbx_builtin_getvar_helper(chan, "AGENTWRAPUPTIME") && strlen(pbx_builtin_getvar_helper(chan, "AGENTWRAPUPTIME"))) {
02068                p->wrapuptime = atoi(pbx_builtin_getvar_helper(chan, "AGENTWRAPUPTIME"));
02069                if (p->wrapuptime < 0)
02070                   p->wrapuptime = 0;
02071                tmpoptions=pbx_builtin_getvar_helper(chan, "AGENTWRAPUPTIME");
02072                if (option_verbose > 2)
02073                   ast_verbose(VERBOSE_PREFIX_3 "Saw variable AGENTWRAPUPTIME=%s, setting wrapuptime to: %d for Agent '%s'.\n",tmpoptions,p->wrapuptime,p->agent);
02074             } else {
02075                p->wrapuptime = wrapuptime;
02076             }
02077             ast_channel_unlock(chan);
02078             unlock_channel = 0;
02079             /* End Channel Specific Agent Overrides */
02080             if (!p->chan) {
02081                char last_loginchan[80] = "";
02082                long logintime;
02083                snprintf(agent, sizeof(agent), "Agent/%s", p->agent);
02084 
02085                if (callbackmode) {
02086                   int pos = 0;
02087                   /* Retrieve login chan */
02088                   for (;;) {
02089                      if (!ast_strlen_zero(args.extension)) {
02090                         ast_copy_string(tmpchan, args.extension, sizeof(tmpchan));
02091                         res = 0;
02092                      } else
02093                         res = ast_app_getdata(chan, "agent-newlocation", tmpchan+pos, sizeof(tmpchan) - 2, 0);
02094                      if (ast_strlen_zero(tmpchan) )
02095                         break;
02096                      if(ast_exists_extension(chan, S_OR(context,"default"), tmpchan,1, NULL) ) {
02097                         if(!allow_multiple_login(tmpchan,context) ) {
02098                            args.extension = NULL;
02099                            pos = 0;
02100                         } else
02101                            break;
02102                      }
02103                      if (args.extension) {
02104                         ast_log(LOG_WARNING, "Extension '%s' is not valid for automatic login of agent '%s'\n", args.extension, p->agent);
02105                         args.extension = NULL;
02106                         pos = 0;
02107                      } else {
02108                         ast_log(LOG_WARNING, "Extension '%s@%s' is not valid for automatic login of agent '%s'\n", tmpchan, S_OR(context, "default"), p->agent);
02109                         res = ast_streamfile(chan, "invalid", chan->language);
02110                         if (!res)
02111                            res = ast_waitstream(chan, AST_DIGIT_ANY);
02112                         if (res > 0) {
02113                            tmpchan[0] = res;
02114                            tmpchan[1] = '\0';
02115                            pos = 1;
02116                         } else {
02117                            tmpchan[0] = '\0';
02118                            pos = 0;
02119                         }
02120                      }
02121                   }
02122                   args.extension = tmpchan;
02123                   if (!res) {
02124                      set_agentbycallerid(p->logincallerid, NULL);
02125                      if (!ast_strlen_zero(context) && !ast_strlen_zero(tmpchan))
02126                         snprintf(p->loginchan, sizeof(p->loginchan), "%s@%s", tmpchan, context);
02127                      else {
02128                         ast_copy_string(last_loginchan, p->loginchan, sizeof(last_loginchan));
02129                         ast_copy_string(p->loginchan, tmpchan, sizeof(p->loginchan));
02130                      }
02131                      p->acknowledged = 0;
02132                      if (ast_strlen_zero(p->loginchan)) {
02133                         login_state = 2;
02134                         filename = "agent-loggedoff";
02135                      } else {
02136                         if (chan->cid.cid_num) {
02137                            ast_copy_string(p->logincallerid, chan->cid.cid_num, sizeof(p->logincallerid));
02138                            set_agentbycallerid(p->logincallerid, p->agent);
02139                         } else
02140                            p->logincallerid[0] = '\0';
02141                      }
02142 
02143                      if(update_cdr && chan->cdr)
02144                         snprintf(chan->cdr->channel, sizeof(chan->cdr->channel), "Agent/%s", p->agent);
02145 
02146                   }
02147                } else {
02148                   p->loginchan[0] = '\0';
02149                   p->logincallerid[0] = '\0';
02150                   p->acknowledged = 0;
02151                }
02152                ast_mutex_unlock(&p->lock);
02153                AST_LIST_UNLOCK(&agents);
02154                if( !res && play_announcement==1 )
02155                   res = ast_streamfile(chan, filename, chan->language);
02156                if (!res)
02157                   ast_waitstream(chan, "");
02158                AST_LIST_LOCK(&agents);
02159                ast_mutex_lock(&p->lock);
02160                if (!res) {
02161                   res = ast_set_read_format(chan, ast_best_codec(chan->nativeformats));
02162                   if (res)
02163                      ast_log(LOG_WARNING, "Unable to set read format to %d\n", ast_best_codec(chan->nativeformats));
02164                }
02165                if (!res) {
02166                   res = ast_set_write_format(chan, ast_best_codec(chan->nativeformats));
02167                   if (res)
02168                      ast_log(LOG_WARNING, "Unable to set write format to %d\n", ast_best_codec(chan->nativeformats));
02169                }
02170                /* Check once more just in case */
02171                if (p->chan)
02172                   res = -1;
02173                if (callbackmode && !res) {
02174                   /* Just say goodbye and be done with it */
02175                   if (!ast_strlen_zero(p->loginchan)) {
02176                      if (p->loginstart == 0)
02177                         time(&p->loginstart);
02178                      manager_event(EVENT_FLAG_AGENT, "Agentcallbacklogin",
02179                               "Agent: %s\r\n"
02180                               "Loginchan: %s\r\n"
02181                               "Uniqueid: %s\r\n",
02182                               p->agent, p->loginchan, chan->uniqueid);
02183                      ast_queue_log("NONE", chan->uniqueid, agent, "AGENTCALLBACKLOGIN", "%s", p->loginchan);
02184                      if (option_verbose > 1)
02185                         ast_verbose(VERBOSE_PREFIX_2 "Callback Agent '%s' logged in on %s\n", p->agent, p->loginchan);
02186                      ast_device_state_changed("Agent/%s", p->agent);
02187                      if (persistent_agents)
02188                         dump_agents();
02189                   } else {
02190                      logintime = time(NULL) - p->loginstart;
02191                      p->loginstart = 0;
02192 
02193                      agent_logoff_maintenance(p, last_loginchan, logintime, chan->uniqueid, NULL);
02194                      if (option_verbose > 1)
02195                         ast_verbose(VERBOSE_PREFIX_2 "Callback Agent '%s' logged out\n", p->agent);
02196                   }
02197                   AST_LIST_UNLOCK(&agents);
02198                   if (!res)
02199                      res = ast_safe_sleep(chan, 500);
02200                   ast_mutex_unlock(&p->lock);
02201                } else if (!res) {
02202                   ast_indicate_data(chan, AST_CONTROL_HOLD, 
02203                      S_OR(p->moh, NULL), 
02204                      !ast_strlen_zero(p->moh) ? strlen(p->moh) + 1 : 0);
02205                   if (p->loginstart == 0)
02206                      time(&p->loginstart);
02207                   manager_event(EVENT_FLAG_AGENT, "Agentlogin",
02208                            "Agent: %s\r\n"
02209                            "Channel: %s\r\n"
02210                            "Uniqueid: %s\r\n",
02211                            p->agent, chan->name, chan->uniqueid);
02212                   if (update_cdr && chan->cdr)
02213                      snprintf(chan->cdr->channel, sizeof(chan->cdr->channel), "Agent/%s", p->agent);
02214                   ast_queue_log("NONE", chan->uniqueid, agent, "AGENTLOGIN", "%s", chan->name);
02215                   if (option_verbose > 1)
02216                      ast_verbose(VERBOSE_PREFIX_2 "Agent '%s' logged in (format %s/%s)\n", p->agent,
02217                             ast_getformatname(chan->readformat), ast_getformatname(chan->writeformat));
02218                   /* Login this channel and wait for it to go away */
02219                   p->chan = chan;
02220                   if (p->ackcall > 1)
02221                      check_beep(p, 0);
02222                   else
02223                      check_availability(p, 0);
02224                   ast_mutex_unlock(&p->lock);
02225                   AST_LIST_UNLOCK(&agents);
02226                   ast_device_state_changed("Agent/%s", p->agent);
02227                   while (res >= 0) {
02228                      ast_mutex_lock(&p->lock);
02229                      if (p->deferlogoff && p->chan) {
02230                         ast_softhangup(p->chan, AST_SOFTHANGUP_EXPLICIT);
02231                         p->deferlogoff = 0;
02232                      }
02233                      if (p->chan != chan)
02234                         res = -1;
02235                      ast_mutex_unlock(&p->lock);
02236                      /* Yield here so other interested threads can kick in. */
02237                      sched_yield();
02238                      if (res)
02239                         break;
02240 
02241                      AST_LIST_LOCK(&agents);
02242                      ast_mutex_lock(&p->lock);
02243                      if (p->lastdisc.tv_sec) {
02244                         if (ast_tvdiff_ms(ast_tvnow(), p->lastdisc) > 0) {
02245                            if (option_debug)
02246                               ast_log(LOG_DEBUG, "Wrapup time for %s expired!\n", p->agent);
02247                            p->lastdisc = ast_tv(0, 0);
02248                            ast_device_state_changed("Agent/%s", p->agent);
02249                            if (p->ackcall > 1)
02250                               check_beep(p, 0);
02251                            else
02252                               check_availability(p, 0);
02253                         }
02254                      }
02255                      ast_mutex_unlock(&p->lock);
02256                      AST_LIST_UNLOCK(&agents);
02257                      /* Synchronize channel ownership between call to agent and itself. */
02258                      ast_mutex_lock( &p->app_lock );
02259                      ast_mutex_lock(&p->lock);
02260                      p->owning_app = pthread_self();
02261                      ast_mutex_unlock(&p->lock);
02262                      if (p->ackcall > 1) 
02263                         res = agent_ack_sleep(p);
02264                      else
02265                         res = ast_safe_sleep_conditional( chan, 1000, agent_cont_sleep, p );
02266                      ast_mutex_unlock( &p->app_lock );
02267                      if ((p->ackcall > 1)  && (res == 1)) {
02268                         AST_LIST_LOCK(&agents);
02269                         ast_mutex_lock(&p->lock);
02270                         check_availability(p, 0);
02271                         ast_mutex_unlock(&p->lock);
02272                         AST_LIST_UNLOCK(&agents);
02273                         res = 0;
02274                      }
02275                      sched_yield();
02276                   }
02277                   ast_mutex_lock(&p->lock);
02278                   if (res && p->owner) 
02279                      ast_log(LOG_WARNING, "Huh?  We broke out when there was still an owner?\n");
02280                   /* Log us off if appropriate */
02281                   if (p->chan == chan) {
02282                      p->chan = NULL;
02283                      p->inherited_devicestate = -1;
02284                   }
02285                   p->acknowledged = 0;
02286                   logintime = time(NULL) - p->loginstart;
02287                   p->loginstart = 0;
02288                   ast_mutex_unlock(&p->lock);
02289                   manager_event(EVENT_FLAG_AGENT, "Agentlogoff",
02290                            "Agent: %s\r\n"
02291                            "Logintime: %ld\r\n"
02292                            "Uniqueid: %s\r\n",
02293                            p->agent, logintime, chan->uniqueid);
02294                   ast_queue_log("NONE", chan->uniqueid, agent, "AGENTLOGOFF", "%s|%ld", chan->name, logintime);
02295                   if (option_verbose > 1)
02296                      ast_verbose(VERBOSE_PREFIX_2 "Agent '%s' logged out\n", p->agent);
02297                   /* If there is no owner, go ahead and kill it now */
02298                   ast_device_state_changed("Agent/%s", p->agent);
02299                   if (p->dead && !p->owner) {
02300                      ast_mutex_destroy(&p->lock);
02301                      ast_mutex_destroy(&p->app_lock);
02302                      free(p);
02303                   }
02304                }
02305                else {
02306                   ast_mutex_unlock(&p->lock);
02307                   p = NULL;
02308                }
02309                res = -1;
02310             } else {
02311                ast_mutex_unlock(&p->lock);
02312                errmsg = "agent-alreadyon";
02313                p = NULL;
02314             }
02315             break;
02316          }
02317          ast_mutex_unlock(&p->lock);
02318          if (unlock_channel) {
02319             ast_channel_unlock(chan);
02320          }
02321       }
02322       if (!p)
02323          AST_LIST_UNLOCK(&agents);
02324 
02325       if (!res && (max_login_tries==0 || tries < max_login_tries))
02326          res = ast_app_getdata(chan, errmsg, user, sizeof(user) - 1, 0);
02327    }
02328       
02329    if (!res)
02330       res = ast_safe_sleep(chan, 500);
02331 
02332    /* AgentLogin() exit */
02333    if (!callbackmode) {
02334       ast_module_user_remove(u);
02335       return -1;
02336    } else { /* AgentCallbackLogin() exit*/
02337       /* Set variables */
02338       if (login_state > 0) {
02339          pbx_builtin_setvar_helper(chan, "AGENTNUMBER", user);
02340          if (login_state==1) {
02341             pbx_builtin_setvar_helper(chan, "AGENTSTATUS", "on");
02342             pbx_builtin_setvar_helper(chan, "AGENTEXTEN", args.extension);
02343          } else 
02344             pbx_builtin_setvar_helper(chan, "AGENTSTATUS", "off");
02345       } else {
02346          pbx_builtin_setvar_helper(chan, "AGENTSTATUS", "fail");
02347       }
02348       if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 1, chan->cid.cid_num)) {
02349          ast_module_user_remove(u);
02350          return 0;
02351       }
02352       /* Do we need to play agent-goodbye now that we will be hanging up? */
02353       if (play_announcement) {
02354          if (!res)
02355             res = ast_safe_sleep(chan, 1000);
02356          res = ast_streamfile(chan, agent_goodbye, chan->language);
02357          if (!res)
02358             res = ast_waitstream(chan, "");
02359          if (!res)
02360             res = ast_safe_sleep(chan, 1000);
02361       }
02362    }
02363 
02364    ast_module_user_remove(u);
02365    
02366    /* We should never get here if next priority exists when in callbackmode */
02367    return -1;
02368 }
02369 
02370 /*!
02371  * Called by the AgentLogin application (from the dial plan).
02372  * 
02373  * \param chan
02374  * \param data
02375  * \returns
02376  * \sa callback_login_exec(), agentmonitoroutgoing_exec(), load_module().
02377  */
02378 static int login_exec(struct ast_channel *chan, void *data)
02379 {
02380    return __login_exec(chan, data, 0);
02381 }
02382 
02383 static void callback_deprecated(void)
02384 {
02385    static int depwarning = 0;
02386 
02387    if (!depwarning) {
02388       depwarning = 1;
02389 
02390       ast_log(LOG_WARNING, "AgentCallbackLogin is deprecated and will be removed in a future release.\n");
02391       ast_log(LOG_WARNING, "See doc/queues-with-callback-members.txt for an example of how to achieve\n");
02392       ast_log(LOG_WARNING, "the same functionality using only dialplan logic.\n");
02393    }
02394 }
02395 
02396 /*!
02397  *  Called by the AgentCallbackLogin application (from the dial plan).
02398  * 
02399  * \param chan
02400  * \param data
02401  * \returns
02402  * \sa login_exec(), agentmonitoroutgoing_exec(), load_module().
02403  */
02404 static int callback_exec(struct ast_channel *chan, void *data)
02405 {
02406    callback_deprecated();
02407 
02408    return __login_exec(chan, data, 1);
02409 }
02410 
02411 /*!
02412  * Sets an agent as logged in by callback in the Manager API.
02413  * It is registered on load_module() and it gets called by the manager backend.
02414  * \param s
02415  * \param m
02416  * \returns 
02417  * \sa action_agents(), action_agent_logoff(), load_module().
02418  */
02419 static int action_agent_callback_login(struct mansession *s, const struct message *m)
02420 {
02421    const char *agent = astman_get_header(m, "Agent");
02422    const char *exten = astman_get_header(m, "Exten");
02423    const char *context = astman_get_header(m, "Context");
02424    const char *wrapuptime_s = astman_get_header(m, "WrapupTime");
02425    const char *ackcall_s = astman_get_header(m, "AckCall");
02426    struct agent_pvt *p;
02427    int login_state = 0;
02428 
02429    callback_deprecated();
02430 
02431    if (ast_strlen_zero(agent)) {
02432       astman_send_error(s, m, "No agent specified");
02433       return 0;
02434    }
02435 
02436    if (ast_strlen_zero(exten)) {
02437       astman_send_error(s, m, "No extension specified");
02438       return 0;
02439    }
02440 
02441    AST_LIST_LOCK(&agents);
02442    AST_LIST_TRAVERSE(&agents, p, list) {
02443       if (strcmp(p->agent, agent) || p->pending) 
02444          continue;
02445       if (p->chan) {
02446          login_state = 2; /* already logged in (and on the phone)*/
02447          break;
02448       }
02449       ast_mutex_lock(&p->lock);
02450       login_state = 1; /* Successful Login */
02451       
02452       if (ast_strlen_zero(context))
02453          ast_copy_string(p->loginchan, exten, sizeof(p->loginchan));
02454       else
02455          snprintf(p->loginchan, sizeof(p->loginchan), "%s@%s", exten, context);
02456 
02457       if (!ast_strlen_zero(wrapuptime_s)) {
02458          p->wrapuptime = atoi(wrapuptime_s);
02459          if (p->wrapuptime < 0)
02460             p->wrapuptime = 0;
02461       }
02462 
02463       if (!strcasecmp(ackcall_s, "always"))
02464          p->ackcall = 2;
02465       else if (ast_true(ackcall_s))
02466          p->ackcall = 1;
02467       else
02468          p->ackcall = 0;
02469 
02470       if (p->loginstart == 0)
02471          time(&p->loginstart);
02472       manager_event(EVENT_FLAG_AGENT, "Agentcallbacklogin",
02473                "Agent: %s\r\n"
02474                "Loginchan: %s\r\n",
02475                p->agent, p->loginchan);
02476       ast_queue_log("NONE", "NONE", agent, "AGENTCALLBACKLOGIN", "%s", p->loginchan);
02477       if (option_verbose > 1)
02478          ast_verbose(VERBOSE_PREFIX_2 "Callback Agent '%s' logged in on %s\n", p->agent, p->loginchan);
02479       ast_device_state_changed("Agent/%s", p->agent);
02480       ast_mutex_unlock(&p->lock);
02481       if (persistent_agents)
02482          dump_agents();
02483    }
02484    AST_LIST_UNLOCK(&agents);
02485 
02486    if (login_state == 1)
02487       astman_send_ack(s, m, "Agent logged in");
02488    else if (login_state == 0)
02489       astman_send_error(s, m, "No such agent");
02490    else if (login_state == 2)
02491       astman_send_error(s, m, "Agent already logged in");
02492 
02493    return 0;
02494 }
02495 
02496 /*!
02497  *  \brief Called by the AgentMonitorOutgoing application (from the dial plan).
02498  *
02499  * \param chan
02500  * \param data
02501  * \returns
02502  * \sa login_exec(), callback_login_exec(), load_module().
02503  */
02504 static int agentmonitoroutgoing_exec(struct ast_channel *chan, void *data)
02505 {
02506    int exitifnoagentid = 0;
02507    int nowarnings = 0;
02508    int changeoutgoing = 0;
02509    int res = 0;
02510    char agent[AST_MAX_AGENT];
02511 
02512    if (data) {
02513       if (strchr(data, 'd'))
02514          exitifnoagentid = 1;
02515       if (strchr(data, 'n'))
02516          nowarnings = 1;
02517       if (strchr(data, 'c'))
02518          changeoutgoing = 1;
02519    }
02520    if (chan->cid.cid_num) {
02521       const char *tmp;
02522       char agentvar[AST_MAX_BUF];
02523       snprintf(agentvar, sizeof(agentvar), "%s_%s", GETAGENTBYCALLERID, chan->cid.cid_num);
02524       if ((tmp = pbx_builtin_getvar_helper(NULL, agentvar))) {
02525          struct agent_pvt *p;
02526          ast_copy_string(agent, tmp, sizeof(agent));
02527          AST_LIST_LOCK(&agents);
02528          AST_LIST_TRAVERSE(&agents, p, list) {
02529             if (!strcasecmp(p->agent, tmp)) {
02530                if (changeoutgoing) snprintf(chan->cdr->channel, sizeof(chan->cdr->channel), "Agent/%s", p->agent);
02531                __agent_start_monitoring(chan, p, 1);
02532                break;
02533             }
02534          }
02535          AST_LIST_UNLOCK(&agents);
02536          
02537       } else {
02538          res = -1;
02539          if (!nowarnings)
02540             ast_log(LOG_WARNING, "Couldn't find the global variable %s, so I can't figure out which agent (if it's an agent) is placing outgoing call.\n", agentvar);
02541       }
02542    } else {
02543       res = -1;
02544       if (!nowarnings)
02545          ast_log(LOG_WARNING, "There is no callerid on that call, so I can't figure out which agent (if it's an agent) is placing outgoing call.\n");
02546    }
02547    /* check if there is n + 101 priority */
02548    /*! \todo XXX Needs to check option priorityjump etc etc */
02549    if (res) {
02550       if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 101, chan->cid.cid_num)) {
02551          chan->priority+=100;
02552          if (option_verbose > 2)
02553             ast_verbose(VERBOSE_PREFIX_3 "Going to %d priority because there is no callerid or the agentid cannot be found.\n",chan->priority);
02554       } else if (exitifnoagentid)
02555          return res;
02556    }
02557    return 0;
02558 }
02559 
02560 /*!
02561  * \brief Dump AgentCallbackLogin agents to the ASTdb database for persistence
02562  */
02563 static void dump_agents(void)
02564 {
02565    struct agent_pvt *cur_agent = NULL;
02566    char buf[256];
02567 
02568    AST_LIST_TRAVERSE(&agents, cur_agent, list) {
02569       if (cur_agent->chan)
02570          continue;
02571 
02572       if (!ast_strlen_zero(cur_agent->loginchan)) {
02573          snprintf(buf, sizeof(buf), "%s;%s", cur_agent->loginchan, cur_agent->logincallerid);
02574          if (ast_db_put(pa_family, cur_agent->agent, buf))
02575             ast_log(LOG_WARNING, "failed to create persistent entry in ASTdb for %s!\n", buf);
02576          else if (option_debug)
02577             ast_log(LOG_DEBUG, "Saved Agent: %s on %s\n", cur_agent->agent, cur_agent->loginchan);
02578       } else {
02579          /* Delete -  no agent or there is an error */
02580          ast_db_del(pa_family, cur_agent->agent);
02581       }
02582    }
02583 }
02584 
02585 /*!
02586  * \brief Reload the persistent agents from astdb.
02587  */
02588 static void reload_agents(void)
02589 {
02590    char *agent_num;
02591    struct ast_db_entry *db_tree;
02592    struct ast_db_entry *entry;
02593    struct agent_pvt *cur_agent;
02594    char agent_data[256];
02595    char *parse;
02596    char *agent_chan;
02597    char *agent_callerid;
02598 
02599    db_tree = ast_db_gettree(pa_family, NULL);
02600 
02601    AST_LIST_LOCK(&agents);
02602    for (entry = db_tree; entry; entry = entry->next) {
02603       agent_num = entry->key + strlen(pa_family) + 2;
02604       AST_LIST_TRAVERSE(&agents, cur_agent, list) {
02605          ast_mutex_lock(&cur_agent->lock);
02606          if (strcmp(agent_num, cur_agent->agent) == 0)
02607             break;
02608          ast_mutex_unlock(&cur_agent->lock);
02609       }
02610       if (!cur_agent) {
02611          ast_db_del(pa_family, agent_num);
02612          continue;
02613       } else
02614          ast_mutex_unlock(&cur_agent->lock);
02615       if (!ast_db_get(pa_family, agent_num, agent_data, sizeof(agent_data)-1)) {
02616          if (option_debug)
02617             ast_log(LOG_DEBUG, "Reload Agent from AstDB: %s on %s\n", cur_agent->agent, agent_data);
02618          parse = agent_data;
02619          agent_chan = strsep(&parse, ";");
02620          agent_callerid = strsep(&parse, ";");
02621          ast_copy_string(cur_agent->loginchan, agent_chan, sizeof(cur_agent->loginchan));
02622          if (agent_callerid) {
02623             ast_copy_string(cur_agent->logincallerid, agent_callerid, sizeof(cur_agent->logincallerid));
02624             set_agentbycallerid(cur_agent->logincallerid, cur_agent->agent);
02625          } else
02626             cur_agent->logincallerid[0] = '\0';
02627          if (cur_agent->loginstart == 0)
02628             time(&cur_agent->loginstart);
02629          ast_device_state_changed("Agent/%s", cur_agent->agent);  
02630       }
02631    }
02632    AST_LIST_UNLOCK(&agents);
02633    if (db_tree) {
02634       ast_log(LOG_NOTICE, "Agents successfully reloaded from database.\n");
02635       ast_db_freetree(db_tree);
02636    }
02637 }
02638 
02639 /*! \brief Part of PBX channel interface */
02640 static int agent_devicestate(void *data)
02641 {
02642    struct agent_pvt *p;
02643    char *s;
02644    ast_group_t groupmatch;
02645    int groupoff;
02646    int waitforagent=0;
02647    int res = AST_DEVICE_INVALID;
02648    
02649    s = data;
02650    if ((s[0] == '@') && (sscanf(s + 1, "%d", &groupoff) == 1))
02651       groupmatch = (1 << groupoff);
02652    else if ((s[0] == ':') && (sscanf(s + 1, "%d", &groupoff) == 1)) {
02653       groupmatch = (1 << groupoff);
02654       waitforagent = 1;
02655    } else 
02656       groupmatch = 0;
02657 
02658    /* Check actual logged in agents first */
02659    AST_LIST_LOCK(&agents);
02660    AST_LIST_TRAVERSE(&agents, p, list) {
02661       ast_mutex_lock(&p->lock);
02662       if (!p->pending && ((groupmatch && (p->group & groupmatch)) || !strcmp(data, p->agent))) {
02663          if (p->owner) {
02664             if (res != AST_DEVICE_INUSE)
02665                res = AST_DEVICE_BUSY;
02666          } else if (p->inherited_devicestate > -1) {
02667             res = p->inherited_devicestate;
02668          } else {
02669             if (res == AST_DEVICE_BUSY)
02670                res = AST_DEVICE_INUSE;
02671             if (p->chan || !ast_strlen_zero(p->loginchan)) {
02672                if (res == AST_DEVICE_INVALID)
02673                   res = AST_DEVICE_UNKNOWN;
02674             } else if (res == AST_DEVICE_INVALID)  
02675                res = AST_DEVICE_UNAVAILABLE;
02676          }
02677          if (!strcmp(data, p->agent)) {
02678             ast_mutex_unlock(&p->lock);
02679             break;
02680          }
02681       }
02682       ast_mutex_unlock(&p->lock);
02683    }
02684    AST_LIST_UNLOCK(&agents);
02685    return res;
02686 }
02687 
02688 /*!
02689  * \note This function expects the agent list to be locked
02690  */
02691 static struct agent_pvt *find_agent(char *agentid)
02692 {
02693    struct agent_pvt *cur;
02694 
02695    AST_LIST_TRAVERSE(&agents, cur, list) {
02696       if (!strcmp(cur->agent, agentid))
02697          break;   
02698    }
02699 
02700    return cur; 
02701 }
02702 
02703 static int function_agent(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
02704 {
02705    char *parse;    
02706    AST_DECLARE_APP_ARGS(args,
02707       AST_APP_ARG(agentid);
02708       AST_APP_ARG(item);
02709    );
02710    char *tmp;
02711    struct agent_pvt *agent;
02712 
02713    buf[0] = '\0';
02714 
02715    if (ast_strlen_zero(data)) {
02716       ast_log(LOG_WARNING, "The AGENT function requires an argument - agentid!\n");
02717       return -1;
02718    }
02719 
02720    parse = ast_strdupa(data);
02721 
02722    AST_NONSTANDARD_APP_ARGS(args, parse, ':');
02723    if (!args.item)
02724       args.item = "status";
02725 
02726    AST_LIST_LOCK(&agents);
02727 
02728    if (!(agent = find_agent(args.agentid))) {
02729       AST_LIST_UNLOCK(&agents);
02730       ast_log(LOG_WARNING, "Agent '%s' not found!\n", args.agentid);
02731       return -1;
02732    }
02733 
02734    if (!strcasecmp(args.item, "status")) {
02735       char *status = "LOGGEDOUT";
02736       if (agent->chan || !ast_strlen_zero(agent->loginchan)) 
02737          status = "LOGGEDIN"; 
02738       ast_copy_string(buf, status, len);
02739    } else if (!strcasecmp(args.item, "password")) 
02740       ast_copy_string(buf, agent->password, len);
02741    else if (!strcasecmp(args.item, "name"))
02742       ast_copy_string(buf, agent->name, len);
02743    else if (!strcasecmp(args.item, "mohclass"))
02744       ast_copy_string(buf, agent->moh, len);
02745    else if (!strcasecmp(args.item, "channel")) {
02746       if (agent->chan) {
02747          ast_copy_string(buf, agent->chan->name, len);
02748          tmp = strrchr(buf, '-');
02749          if (tmp)
02750             *tmp = '\0';
02751       } 
02752    } else if (!strcasecmp(args.item, "exten"))
02753       ast_copy_string(buf, agent->loginchan, len); 
02754 
02755    AST_LIST_UNLOCK(&agents);
02756 
02757    return 0;
02758 }
02759 
02760 struct ast_custom_function agent_function = {
02761    .name = "AGENT",
02762    .synopsis = "Gets information about an Agent",
02763    .syntax = "AGENT(<agentid>[:item])",
02764    .read = function_agent,
02765    .desc = "The valid items to retrieve are:\n"
02766    "- status (default)      The status of the agent\n"
02767    "                          LOGGEDIN | LOGGEDOUT\n"
02768    "- password              The password of the agent\n"
02769    "- name                  The name of the agent\n"
02770    "- mohclass              MusicOnHold class\n"
02771    "- exten                 The callback extension for the Agent (AgentCallbackLogin)\n"
02772    "- channel               The name of the active channel for the Agent (AgentLogin)\n"
02773 };
02774 
02775 
02776 /*!
02777  * \brief Initialize the Agents module.
02778  * This function is being called by Asterisk when loading the module. 
02779  * Among other things it registers applications, cli commands and reads the cofiguration file.
02780  *
02781  * \returns int Always 0.
02782  */
02783 static int load_module(void)
02784 {
02785    /* Make sure we can register our agent channel type */
02786    if (ast_channel_register(&agent_tech)) {
02787       ast_log(LOG_ERROR, "Unable to register channel class 'Agent'\n");
02788       return -1;
02789    }
02790    /* Read in the config */
02791    if (!read_agent_config())
02792       return AST_MODULE_LOAD_DECLINE;
02793    if (persistent_agents)
02794       reload_agents();
02795    /* Dialplan applications */
02796    ast_register_application(app, login_exec, synopsis, descrip);
02797    ast_register_application(app2, callback_exec, synopsis2, descrip2);
02798    ast_register_application(app3, agentmonitoroutgoing_exec, synopsis3, descrip3);
02799 
02800    /* Manager commands */
02801    ast_manager_register2("Agents", EVENT_FLAG_AGENT, action_agents, "Lists agents and their status", mandescr_agents);
02802    ast_manager_register2("AgentLogoff", EVENT_FLAG_AGENT, action_agent_logoff, "Sets an agent as no longer logged in", mandescr_agent_logoff);
02803    ast_manager_register2("AgentCallbackLogin", EVENT_FLAG_AGENT, action_agent_callback_login, "Sets an agent as logged in by callback", mandescr_agent_callback_login);
02804 
02805    /* CLI Commands */
02806    ast_cli_register_multiple(cli_agents, sizeof(cli_agents) / sizeof(struct ast_cli_entry));
02807 
02808    /* Dialplan Functions */
02809    ast_custom_function_register(&agent_function);
02810 
02811    ast_devstate_add(agent_devicestate_cb, NULL);
02812 
02813    return 0;
02814 }
02815 
02816 static int reload(void)
02817 {
02818    read_agent_config();
02819    if (persistent_agents)
02820       reload_agents();
02821    return 0;
02822 }
02823 
02824 static int unload_module(void)
02825 {
02826    struct agent_pvt *p;
02827    /* First, take us out of the channel loop */
02828    ast_channel_unregister(&agent_tech);
02829    /* Delete devicestate subscription */
02830    ast_devstate_del(agent_devicestate_cb, NULL);
02831    /* Unregister dialplan functions */
02832    ast_custom_function_unregister(&agent_function);   
02833    /* Unregister CLI commands */
02834    ast_cli_unregister_multiple(cli_agents, sizeof(cli_agents) / sizeof(struct ast_cli_entry));
02835    /* Unregister dialplan applications */
02836    ast_unregister_application(app);
02837    ast_unregister_application(app2);
02838    ast_unregister_application(app3);
02839    /* Unregister manager command */
02840    ast_manager_unregister("Agents");
02841    ast_manager_unregister("AgentLogoff");
02842    ast_manager_unregister("AgentCallbackLogin");
02843    /* Unregister channel */
02844    AST_LIST_LOCK(&agents);
02845    /* Hangup all interfaces if they have an owner */
02846    while ((p = AST_LIST_REMOVE_HEAD(&agents, list))) {
02847       if (p->owner)
02848          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
02849       free(p);
02850    }
02851    AST_LIST_UNLOCK(&agents);
02852    return 0;
02853 }
02854 
02855 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Agent Proxy Channel",
02856       .load = load_module,
02857       .unload = unload_module,
02858       .reload = reload,
02859           );

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