Merged revisions 7986 via svnmerge from
[asterisk/asterisk.git] / channels / chan_agent.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19
20 /*! \file
21  * 
22  * \brief Implementation of Agents (proxy channel)
23  *
24  * \author Mark Spencer <markster@digium.com>
25  *
26  * This file is the implementation of Agents modules.
27  * It is a dynamic module that is loaded by Asterisk. 
28  * \par See also
29  * \arg \ref Config_agent
30  *
31  * \ingroup channel_drivers
32  */
33
34 #include <stdio.h>
35 #include <string.h>
36 #include <errno.h>
37 #include <unistd.h>
38 #include <sys/socket.h>
39 #include <stdlib.h>
40 #include <fcntl.h>
41 #include <netdb.h>
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
44 #include <sys/signal.h>
45
46 #include "asterisk.h"
47
48 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
49
50 #include "asterisk/lock.h"
51 #include "asterisk/channel.h"
52 #include "asterisk/config.h"
53 #include "asterisk/logger.h"
54 #include "asterisk/module.h"
55 #include "asterisk/pbx.h"
56 #include "asterisk/options.h"
57 #include "asterisk/lock.h"
58 #include "asterisk/sched.h"
59 #include "asterisk/io.h"
60 #include "asterisk/rtp.h"
61 #include "asterisk/acl.h"
62 #include "asterisk/callerid.h"
63 #include "asterisk/file.h"
64 #include "asterisk/cli.h"
65 #include "asterisk/app.h"
66 #include "asterisk/musiconhold.h"
67 #include "asterisk/manager.h"
68 #include "asterisk/features.h"
69 #include "asterisk/utils.h"
70 #include "asterisk/causes.h"
71 #include "asterisk/astdb.h"
72 #include "asterisk/devicestate.h"
73 #include "asterisk/monitor.h"
74
75 static const char desc[] = "Agent Proxy Channel";
76 static const char channeltype[] = "Agent";
77 static const char tdesc[] = "Call Agent Proxy Channel";
78 static const char config[] = "agents.conf";
79
80 static const char app[] = "AgentLogin";
81 static const char app2[] = "AgentCallbackLogin";
82 static const char app3[] = "AgentMonitorOutgoing";
83
84 static const char synopsis[] = "Call agent login";
85 static const char synopsis2[] = "Call agent callback login";
86 static const char synopsis3[] = "Record agent's outgoing call";
87
88 static const char descrip[] =
89 "  AgentLogin([AgentNo][|options]):\n"
90 "Asks the agent to login to the system.  Always returns -1.  While\n"
91 "logged in, the agent can receive calls and will hear a 'beep'\n"
92 "when a new call comes in. The agent can dump the call by pressing\n"
93 "the star key.\n"
94 "The option string may contain zero or more of the following characters:\n"
95 "      's' -- silent login - do not announce the login ok segment after agent logged in/off\n";
96
97 static const char descrip2[] =
98 "  AgentCallbackLogin([AgentNo][|[options][|[exten]@context]]):\n"
99 "Asks the agent to login to the system with callback.\n"
100 "The agent's callback extension is called (optionally with the specified\n"
101 "context).\n"
102 "The option string may contain zero or more of the following characters:\n"
103 "      's' -- silent login - do not announce the login ok segment agent logged in/off\n";
104
105 static const char descrip3[] =
106 "  AgentMonitorOutgoing([options]):\n"
107 "Tries to figure out the id of the agent who is placing outgoing call based on\n"
108 "comparision of the callerid of the current interface and the global variable \n"
109 "placed by the AgentCallbackLogin application. That's why it should be used only\n"
110 "with the AgentCallbackLogin app. Uses the monitoring functions in chan_agent \n"
111 "instead of Monitor application. That have to be configured in the agents.conf file.\n"
112 "\nReturn value:\n"
113 "Normally the app returns 0 unless the options are passed. Also if the callerid or\n"
114 "the agentid are not specified it'll look for n+101 priority.\n"
115 "\nOptions:\n"
116 "       'd' - make the app return -1 if there is an error condition and there is\n"
117 "             no extension n+101\n"
118 "       'c' - change the CDR so that the source of the call is 'Agent/agent_id'\n"
119 "       'n' - don't generate the warnings when there is no callerid or the\n"
120 "             agentid is not known.\n"
121 "             It's handy if you want to have one context for agent and non-agent calls.\n";
122
123 static const char mandescr_agents[] =
124 "Description: Will list info about all possible agents.\n"
125 "Variables: NONE\n";
126
127 static const char mandescr_agent_logoff[] =
128 "Description: Sets an agent as no longer logged in.\n"
129 "Variables: (Names marked with * are required)\n"
130 "       *Agent: Agent ID of the agent to log off\n"
131 "       Soft: Set to 'true' to not hangup existing calls\n";
132
133 static const char mandescr_agent_callback_login[] =
134 "Description: Sets an agent as logged in with callback.\n"
135 "Variables: (Names marked with * are required)\n"
136 "       *Agent: Agent ID of the agent to login\n"
137 "       *Exten: Extension to use for callback\n"
138 "       Context: Context to use for callback\n"
139 "       AckCall: Set to 'true' to require an acknowledgement by '#' when agent is called back\n"
140 "       WrapupTime: the minimum amount of time after disconnecting before the caller can receive a new call\n";
141
142 static char moh[80] = "default";
143
144 #define AST_MAX_AGENT   80              /**< Agent ID or Password max length */
145 #define AST_MAX_BUF     256
146 #define AST_MAX_FILENAME_LEN    256
147
148 /** Persistent Agents astdb family */
149 static const char pa_family[] = "/Agents";
150 /** The maximum lengh of each persistent member agent database entry */
151 #define PA_MAX_LEN 2048
152 /** queues.conf [general] option */
153 static int persistent_agents = 0;
154 static void dump_agents(void);
155
156 static ast_group_t group;
157 static int autologoff;
158 static int wrapuptime;
159 static int ackcall;
160
161 static int maxlogintries = 3;
162 static char agentgoodbye[AST_MAX_FILENAME_LEN] = "vm-goodbye";
163
164 static int usecnt =0;
165 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
166
167 /* Protect the interface list (of pvt's) */
168 AST_MUTEX_DEFINE_STATIC(agentlock);
169
170 static int recordagentcalls = 0;
171 static char recordformat[AST_MAX_BUF] = "";
172 static char recordformatext[AST_MAX_BUF] = "";
173 static int createlink = 0;
174 static char urlprefix[AST_MAX_BUF] = "";
175 static char savecallsin[AST_MAX_BUF] = "";
176 static int updatecdr = 0;
177 static char beep[AST_MAX_BUF] = "beep";
178
179 #define GETAGENTBYCALLERID      "AGENTBYCALLERID"
180
181 /**
182  * Structure representing an agent.
183  */
184 struct agent_pvt {
185         ast_mutex_t lock;              /**< Channel private lock */
186         int dead;                      /**< Poised for destruction? */
187         int pending;                   /**< Not a real agent -- just pending a match */
188         int abouttograb;               /**< About to grab */
189         int autologoff;                /**< Auto timeout time */
190         int ackcall;                   /**< ackcall */
191         time_t loginstart;             /**< When agent first logged in (0 when logged off) */
192         time_t start;                  /**< When call started */
193         struct timeval lastdisc;       /**< When last disconnected */
194         int wrapuptime;                /**< Wrapup time in ms */
195         ast_group_t group;             /**< Group memberships */
196         int acknowledged;              /**< Acknowledged */
197         char moh[80];                  /**< Which music on hold */
198         char agent[AST_MAX_AGENT];     /**< Agent ID */
199         char password[AST_MAX_AGENT];  /**< Password for Agent login */
200         char name[AST_MAX_AGENT];
201         ast_mutex_t app_lock;          /**< Synchronization between owning applications */
202         volatile pthread_t owning_app; /**< Owning application thread id */
203         volatile int app_sleep_cond;   /**< Sleep condition for the login app */
204         struct ast_channel *owner;     /**< Agent */
205         char loginchan[80];            /**< channel they logged in from */
206         char logincallerid[80];        /**< Caller ID they had when they logged in */
207         struct ast_channel *chan;      /**< Channel we use */
208         struct agent_pvt *next;        /**< Next Agent in the linked list. */
209 };
210
211 static struct agent_pvt *agents = NULL;  /**< Holds the list of agents (loaded form agents.conf). */
212
213 #define CHECK_FORMATS(ast, p) do { \
214         if (p->chan) {\
215                 if (ast->nativeformats != p->chan->nativeformats) { \
216                         ast_log(LOG_DEBUG, "Native formats changing from %d to %d\n", ast->nativeformats, p->chan->nativeformats); \
217                         /* Native formats changed, reset things */ \
218                         ast->nativeformats = p->chan->nativeformats; \
219                         ast_log(LOG_DEBUG, "Resetting read to %d and write to %d\n", ast->readformat, ast->writeformat);\
220                         ast_set_read_format(ast, ast->readformat); \
221                         ast_set_write_format(ast, ast->writeformat); \
222                 } \
223                 if (p->chan->readformat != ast->rawreadformat)  \
224                         ast_set_read_format(p->chan, ast->rawreadformat); \
225                 if (p->chan->writeformat != ast->rawwriteformat) \
226                         ast_set_write_format(p->chan, ast->rawwriteformat); \
227         } \
228 } while(0)
229
230 /* Cleanup moves all the relevant FD's from the 2nd to the first, but retains things
231    properly for a timingfd XXX This might need more work if agents were logged in as agents or other
232    totally impractical combinations XXX */
233
234 #define CLEANUP(ast, p) do { \
235         int x; \
236         if (p->chan) { \
237                 for (x=0;x<AST_MAX_FDS;x++) {\
238                         if (x != AST_MAX_FDS - 2) \
239                                 ast->fds[x] = p->chan->fds[x]; \
240                 } \
241                 ast->fds[AST_MAX_FDS - 3] = p->chan->fds[AST_MAX_FDS - 2]; \
242         } \
243 } while(0)
244
245 static struct ast_channel *agent_request(const char *type, int format, void *data, int *cause);
246 static int agent_devicestate(void *data);
247 static int agent_digit(struct ast_channel *ast, char digit);
248 static int agent_call(struct ast_channel *ast, char *dest, int timeout);
249 static int agent_hangup(struct ast_channel *ast);
250 static int agent_answer(struct ast_channel *ast);
251 static struct ast_frame *agent_read(struct ast_channel *ast);
252 static int agent_write(struct ast_channel *ast, struct ast_frame *f);
253 static int agent_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen);
254 static int agent_sendtext(struct ast_channel *ast, const char *text);
255 static int agent_indicate(struct ast_channel *ast, int condition);
256 static int agent_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
257 static struct ast_channel *agent_bridgedchannel(struct ast_channel *chan, struct ast_channel *bridge);
258
259 static const struct ast_channel_tech agent_tech = {
260         .type = channeltype,
261         .description = tdesc,
262         .capabilities = -1,
263         .requester = agent_request,
264         .devicestate = agent_devicestate,
265         .send_digit = agent_digit,
266         .call = agent_call,
267         .hangup = agent_hangup,
268         .answer = agent_answer,
269         .read = agent_read,
270         .write = agent_write,
271         .send_html = agent_sendhtml,
272         .send_text = agent_sendtext,
273         .exception = agent_read,
274         .indicate = agent_indicate,
275         .fixup = agent_fixup,
276         .bridged_channel = agent_bridgedchannel,
277 };
278
279 /**
280  * Unlink (that is, take outside of the linked list) an agent.
281  *
282  * @param agent Agent to be unlinked.
283  */
284 static void agent_unlink(struct agent_pvt *agent)
285 {
286         struct agent_pvt *p, *prev;
287         prev = NULL;
288         p = agents;
289         // Iterate over all agents looking for the one.
290         while(p) {
291                 if (p == agent) {
292                         // Once it wal found, check if it is the first one.
293                         if (prev)
294                                 // If it is not, tell the previous agent that the next one is the next one of the current (jumping the current).
295                                 prev->next = agent->next;
296                         else
297                                 // If it is the first one, just change the general pointer to point to the second one.
298                                 agents = agent->next;
299                         // We are done.
300                         break;
301                 }
302                 prev = p;
303                 p = p->next;
304         }
305 }
306
307 /**
308  * Adds an agent to the global list of agents.
309  *
310  * @param agent A string with the username, password and real name of an agent. As defined in agents.conf. Example: "13,169,John Smith"
311  * @param pending If it is pending or not.
312  * @return The just created agent.
313  * @sa agent_pvt, agents.
314  */
315 static struct agent_pvt *add_agent(char *agent, int pending)
316 {
317         int argc;
318         char *argv[3];
319         char *args;
320         char *password = NULL;
321         char *name = NULL;
322         char *agt = NULL;
323         struct agent_pvt *p, *prev;
324
325         args = ast_strdupa(agent);
326
327         // Extract username (agt), password and name from agent (args).
328         if ((argc = ast_app_separate_args(args, ',', argv, sizeof(argv) / sizeof(argv[0])))) {
329                 agt = argv[0];
330                 if (argc > 1) {
331                         password = argv[1];
332                         while (*password && *password < 33) password++;
333                 } 
334                 if (argc > 2) {
335                         name = argv[2];
336                         while (*name && *name < 33) name++;
337                 }
338         } else {
339                 ast_log(LOG_WARNING, "A blank agent line!\n");
340         }
341         
342         // Are we searching for the agent here ? to see if it exists already ?
343         prev=NULL;
344         p = agents;
345         while(p) {
346                 if (!pending && !strcmp(p->agent, agt))
347                         break;
348                 prev = p;
349                 p = p->next;
350         }
351         if (!p) {
352                 // Build the agent.
353                 if (!(p = ast_calloc(1, sizeof(*p))))
354                         return NULL;
355                 ast_copy_string(p->agent, agt, sizeof(p->agent));
356                 ast_mutex_init(&p->lock);
357                 ast_mutex_init(&p->app_lock);
358                 p->owning_app = (pthread_t) -1;
359                 p->app_sleep_cond = 1;
360                 p->group = group;
361                 p->pending = pending;
362                 p->next = NULL;
363                 if (prev)
364                         prev->next = p;
365                 else
366                         agents = p;
367         }
368         
369         ast_copy_string(p->password, password ? password : "", sizeof(p->password));
370         ast_copy_string(p->name, name ? name : "", sizeof(p->name));
371         ast_copy_string(p->moh, moh, sizeof(p->moh));
372         p->ackcall = ackcall;
373         p->autologoff = autologoff;
374
375         /* If someone reduces the wrapuptime and reloads, we want it
376          * to change the wrapuptime immediately on all calls */
377         if (p->wrapuptime > wrapuptime) {
378                 struct timeval now = ast_tvnow();
379                 /* XXX check what is this exactly */
380
381                 /* We won't be pedantic and check the tv_usec val */
382                 if (p->lastdisc.tv_sec > (now.tv_sec + wrapuptime/1000)) {
383                         p->lastdisc.tv_sec = now.tv_sec + wrapuptime/1000;
384                         p->lastdisc.tv_usec = now.tv_usec;
385                 }
386         }
387         p->wrapuptime = wrapuptime;
388
389         if (pending)
390                 p->dead = 1;
391         else
392                 p->dead = 0;
393         return p;
394 }
395
396 /**
397  * Deletes an agent after doing some clean up.
398  * Further documentation: How safe is this function ? What state should the agent be to be cleaned.
399  * @param p Agent to be deleted.
400  * @returns Always 0.
401  */
402 static int agent_cleanup(struct agent_pvt *p)
403 {
404         struct ast_channel *chan = p->owner;
405         p->owner = NULL;
406         chan->tech_pvt = NULL;
407         p->app_sleep_cond = 1;
408         /* Release ownership of the agent to other threads (presumably running the login app). */
409         ast_mutex_unlock(&p->app_lock);
410         if (chan)
411                 ast_channel_free(chan);
412         if (p->dead) {
413                 ast_mutex_destroy(&p->lock);
414                 ast_mutex_destroy(&p->app_lock);
415                 free(p);
416         }
417         return 0;
418 }
419
420 static int check_availability(struct agent_pvt *newlyavailable, int needlock);
421
422 static int agent_answer(struct ast_channel *ast)
423 {
424         ast_log(LOG_WARNING, "Huh?  Agent is being asked to answer?\n");
425         return -1;
426 }
427
428 static int __agent_start_monitoring(struct ast_channel *ast, struct agent_pvt *p, int needlock)
429 {
430         char tmp[AST_MAX_BUF],tmp2[AST_MAX_BUF], *pointer;
431         char filename[AST_MAX_BUF];
432         int res = -1;
433         if (!p)
434                 return -1;
435         if (!ast->monitor) {
436                 snprintf(filename, sizeof(filename), "agent-%s-%s",p->agent, ast->uniqueid);
437                 /* substitute . for - */
438                 if ((pointer = strchr(filename, '.')))
439                         *pointer = '-';
440                 snprintf(tmp, sizeof(tmp), "%s%s",savecallsin ? savecallsin : "", filename);
441                 ast_monitor_start(ast, recordformat, tmp, needlock);
442                 ast_monitor_setjoinfiles(ast, 1);
443                 snprintf(tmp2, sizeof(tmp2), "%s%s.%s", urlprefix ? urlprefix : "", filename, recordformatext);
444 #if 0
445                 ast_verbose("name is %s, link is %s\n",tmp, tmp2);
446 #endif
447                 if (!ast->cdr)
448                         ast->cdr = ast_cdr_alloc();
449                 ast_cdr_setuserfield(ast, tmp2);
450                 res = 0;
451         } else
452                 ast_log(LOG_ERROR, "Recording already started on that call.\n");
453         return res;
454 }
455
456 static int agent_start_monitoring(struct ast_channel *ast, int needlock)
457 {
458         return __agent_start_monitoring(ast, ast->tech_pvt, needlock);
459 }
460
461 static struct ast_frame *agent_read(struct ast_channel *ast)
462 {
463         struct agent_pvt *p = ast->tech_pvt;
464         struct ast_frame *f = NULL;
465         static struct ast_frame null_frame = { AST_FRAME_NULL, };
466         static struct ast_frame answer_frame = { AST_FRAME_CONTROL, AST_CONTROL_ANSWER };
467         ast_mutex_lock(&p->lock); 
468         CHECK_FORMATS(ast, p);
469         if (p->chan) {
470                 ast_copy_flags(p->chan, ast, AST_FLAG_EXCEPTION);
471                 if (ast->fdno == AST_MAX_FDS - 3)
472                         p->chan->fdno = AST_MAX_FDS - 2;
473                 else
474                         p->chan->fdno = ast->fdno;
475                 f = ast_read(p->chan);
476         } else
477                 f = &null_frame;
478         if (!f) {
479                 /* If there's a channel, hang it up (if it's on a callback) make it NULL */
480                 if (p->chan) {
481                         p->chan->_bridge = NULL;
482                         /* Note that we don't hangup if it's not a callback because Asterisk will do it
483                            for us when the PBX instance that called login finishes */
484                         if (!ast_strlen_zero(p->loginchan)) {
485                                 if (p->chan)
486                                         ast_log(LOG_DEBUG, "Bridge on '%s' being cleared (2)\n", p->chan->name);
487                                 ast_hangup(p->chan);
488                                 if (p->wrapuptime && p->acknowledged)
489                                         p->lastdisc = ast_tvadd(ast_tvnow(), ast_samp2tv(p->wrapuptime, 1000));
490                         }
491                         p->chan = NULL;
492                         p->acknowledged = 0;
493                 }
494         } else {
495                 /* if acknowledgement is not required, and the channel is up, we may have missed
496                    an AST_CONTROL_ANSWER (if there was one), so mark the call acknowledged anyway */
497                 if (!p->ackcall && !p->acknowledged && p->chan && (p->chan->_state == AST_STATE_UP))
498                         p->acknowledged = 1;
499                 switch (f->frametype) {
500                 case AST_FRAME_CONTROL:
501                         if (f->subclass == AST_CONTROL_ANSWER) {
502                                 if (p->ackcall) {
503                                         if (option_verbose > 2)
504                                                 ast_verbose(VERBOSE_PREFIX_3 "%s answered, waiting for '#' to acknowledge\n", p->chan->name);
505                                         /* Don't pass answer along */
506                                         ast_frfree(f);
507                                         f = &null_frame;
508                                 } else {
509                                         p->acknowledged = 1;
510                                         /* Use the builtin answer frame for the 
511                                            recording start check below. */
512                                         ast_frfree(f);
513                                         f = &answer_frame;
514                                 }
515                         }
516                         break;
517                 case AST_FRAME_DTMF:
518                         if (!p->acknowledged && (f->subclass == '#')) {
519                                 if (option_verbose > 2)
520                                         ast_verbose(VERBOSE_PREFIX_3 "%s acknowledged\n", p->chan->name);
521                                 p->acknowledged = 1;
522                                 ast_frfree(f);
523                                 f = &answer_frame;
524                         } else if (f->subclass == '*') {
525                                 /* terminates call */
526                                 ast_frfree(f);
527                                 f = NULL;
528                         }
529                         break;
530                 case AST_FRAME_VOICE:
531                         /* don't pass voice until the call is acknowledged */
532                         if (!p->acknowledged) {
533                                 ast_frfree(f);
534                                 f = &null_frame;
535                         }
536                         break;
537                 }
538         }
539
540         CLEANUP(ast,p);
541         if (p->chan && !p->chan->_bridge) {
542                 if (strcasecmp(p->chan->type, "Local")) {
543                         p->chan->_bridge = ast;
544                         if (p->chan)
545                                 ast_log(LOG_DEBUG, "Bridge on '%s' being set to '%s' (3)\n", p->chan->name, p->chan->_bridge->name);
546                 }
547         }
548         ast_mutex_unlock(&p->lock);
549         if (recordagentcalls && f == &answer_frame)
550                 agent_start_monitoring(ast,0);
551         return f;
552 }
553
554 static int agent_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
555 {
556         struct agent_pvt *p = ast->tech_pvt;
557         int res = -1;
558         ast_mutex_lock(&p->lock);
559         if (p->chan) 
560                 res = ast_channel_sendhtml(p->chan, subclass, data, datalen);
561         ast_mutex_unlock(&p->lock);
562         return res;
563 }
564
565 static int agent_sendtext(struct ast_channel *ast, const char *text)
566 {
567         struct agent_pvt *p = ast->tech_pvt;
568         int res = -1;
569         ast_mutex_lock(&p->lock);
570         if (p->chan) 
571                 res = ast_sendtext(p->chan, text);
572         ast_mutex_unlock(&p->lock);
573         return res;
574 }
575
576 static int agent_write(struct ast_channel *ast, struct ast_frame *f)
577 {
578         struct agent_pvt *p = ast->tech_pvt;
579         int res = -1;
580         CHECK_FORMATS(ast, p);
581         ast_mutex_lock(&p->lock);
582         if (p->chan) {
583                 if ((f->frametype != AST_FRAME_VOICE) ||
584                     (f->subclass == p->chan->writeformat)) {
585                         res = ast_write(p->chan, f);
586                 } else {
587                         ast_log(LOG_DEBUG, "Dropping one incompatible voice frame on '%s' to '%s'\n", ast->name, p->chan->name);
588                         res = 0;
589                 }
590         } else
591                 res = 0;
592         CLEANUP(ast, p);
593         ast_mutex_unlock(&p->lock);
594         return res;
595 }
596
597 static int agent_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
598 {
599         struct agent_pvt *p = newchan->tech_pvt;
600         ast_mutex_lock(&p->lock);
601         if (p->owner != oldchan) {
602                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
603                 ast_mutex_unlock(&p->lock);
604                 return -1;
605         }
606         p->owner = newchan;
607         ast_mutex_unlock(&p->lock);
608         return 0;
609 }
610
611 static int agent_indicate(struct ast_channel *ast, int condition)
612 {
613         struct agent_pvt *p = ast->tech_pvt;
614         int res = -1;
615         ast_mutex_lock(&p->lock);
616         if (p->chan)
617                 res = ast_indicate(p->chan, condition);
618         else
619                 res = 0;
620         ast_mutex_unlock(&p->lock);
621         return res;
622 }
623
624 static int agent_digit(struct ast_channel *ast, char digit)
625 {
626         struct agent_pvt *p = ast->tech_pvt;
627         int res = -1;
628         ast_mutex_lock(&p->lock);
629         if (p->chan)
630                 res = p->chan->tech->send_digit(p->chan, digit);
631         else
632                 res = 0;
633         ast_mutex_unlock(&p->lock);
634         return res;
635 }
636
637 static int agent_call(struct ast_channel *ast, char *dest, int timeout)
638 {
639         struct agent_pvt *p = ast->tech_pvt;
640         int res = -1;
641         int newstate=0;
642         ast_mutex_lock(&p->lock);
643         p->acknowledged = 0;
644         if (!p->chan) {
645                 if (p->pending) {
646                         ast_log(LOG_DEBUG, "Pretending to dial on pending agent\n");
647                         newstate = AST_STATE_DIALING;
648                         res = 0;
649                 } else {
650                         ast_log(LOG_NOTICE, "Whoa, they hung up between alloc and call...  what are the odds of that?\n");
651                         res = -1;
652                 }
653                 ast_mutex_unlock(&p->lock);
654                 if (newstate)
655                         ast_setstate(ast, newstate);
656                 return res;
657         } else if (!ast_strlen_zero(p->loginchan)) {
658                 time(&p->start);
659                 /* Call on this agent */
660                 if (option_verbose > 2)
661                         ast_verbose(VERBOSE_PREFIX_3 "outgoing agentcall, to agent '%s', on '%s'\n", p->agent, p->chan->name);
662                 if (p->chan->cid.cid_num)
663                         free(p->chan->cid.cid_num);
664                 p->chan->cid.cid_num = ast_strdup(ast->cid.cid_num);
665                 if (p->chan->cid.cid_name)
666                         free(p->chan->cid.cid_name);
667                 p->chan->cid.cid_name = ast_strdup(ast->cid.cid_name);
668                 ast_channel_inherit_variables(ast, p->chan);
669                 res = ast_call(p->chan, p->loginchan, 0);
670                 CLEANUP(ast,p);
671                 ast_mutex_unlock(&p->lock);
672                 return res;
673         }
674         ast_verbose( VERBOSE_PREFIX_3 "agent_call, call to agent '%s' call on '%s'\n", p->agent, p->chan->name);
675         ast_log( LOG_DEBUG, "Playing beep, lang '%s'\n", p->chan->language);
676         res = ast_streamfile(p->chan, beep, p->chan->language);
677         ast_log( LOG_DEBUG, "Played beep, result '%d'\n", res);
678         if (!res) {
679                 res = ast_waitstream(p->chan, "");
680                 ast_log( LOG_DEBUG, "Waited for stream, result '%d'\n", res);
681         }
682         if (!res) {
683                 res = ast_set_read_format(p->chan, ast_best_codec(p->chan->nativeformats));
684                 ast_log( LOG_DEBUG, "Set read format, result '%d'\n", res);
685                 if (res)
686                         ast_log(LOG_WARNING, "Unable to set read format to %s\n", ast_getformatname(ast_best_codec(p->chan->nativeformats)));
687         } else {
688                 /* Agent hung-up */
689                 p->chan = NULL;
690         }
691
692         if (!res) {
693                 ast_set_write_format(p->chan, ast_best_codec(p->chan->nativeformats));
694                 ast_log( LOG_DEBUG, "Set write format, result '%d'\n", res);
695                 if (res)
696                         ast_log(LOG_WARNING, "Unable to set write format to %s\n", ast_getformatname(ast_best_codec(p->chan->nativeformats)));
697         }
698         if( !res )
699         {
700                 /* Call is immediately up, or might need ack */
701                 if (p->ackcall > 1)
702                         newstate = AST_STATE_RINGING;
703                 else {
704                         newstate = AST_STATE_UP;
705                         if (recordagentcalls)
706                                 agent_start_monitoring(ast,0);
707                         p->acknowledged = 1;
708                 }
709                 res = 0;
710         }
711         CLEANUP(ast,p);
712         ast_mutex_unlock(&p->lock);
713         if (newstate)
714                 ast_setstate(ast, newstate);
715         return res;
716 }
717
718 /* store/clear the global variable that stores agentid based on the callerid */
719 static void set_agentbycallerid(const char *callerid, const char *agent)
720 {
721         char buf[AST_MAX_BUF];
722
723         /* if there is no Caller ID, nothing to do */
724         if (ast_strlen_zero(callerid))
725                 return;
726
727         snprintf(buf, sizeof(buf), "%s_%s",GETAGENTBYCALLERID, callerid);
728         pbx_builtin_setvar_helper(NULL, buf, agent);
729 }
730
731 static int agent_hangup(struct ast_channel *ast)
732 {
733         struct agent_pvt *p = ast->tech_pvt;
734         int howlong = 0;
735         ast_mutex_lock(&p->lock);
736         p->owner = NULL;
737         ast->tech_pvt = NULL;
738         p->app_sleep_cond = 1;
739         p->acknowledged = 0;
740
741         /* if they really are hung up then set start to 0 so the test
742          * later if we're called on an already downed channel
743          * doesn't cause an agent to be logged out like when
744          * agent_request() is followed immediately by agent_hangup()
745          * as in apps/app_chanisavail.c:chanavail_exec()
746          */
747
748         ast_mutex_lock(&usecnt_lock);
749         usecnt--;
750         ast_mutex_unlock(&usecnt_lock);
751
752         ast_log(LOG_DEBUG, "Hangup called for state %s\n", ast_state2str(ast->_state));
753         if (p->start && (ast->_state != AST_STATE_UP)) {
754                 howlong = time(NULL) - p->start;
755                 p->start = 0;
756         } else if (ast->_state == AST_STATE_RESERVED) {
757                 howlong = 0;
758         } else
759                 p->start = 0; 
760         if (p->chan) {
761                 p->chan->_bridge = NULL;
762                 /* If they're dead, go ahead and hang up on the agent now */
763                 if (!ast_strlen_zero(p->loginchan)) {
764                         /* Store last disconnect time */
765                         if (p->wrapuptime)
766                                 p->lastdisc = ast_tvadd(ast_tvnow(), ast_samp2tv(p->wrapuptime, 1000));
767                         else
768                                 p->lastdisc = ast_tv(0,0);
769                         if (p->chan) {
770                                 /* Recognize the hangup and pass it along immediately */
771                                 ast_hangup(p->chan);
772                                 p->chan = NULL;
773                         }
774                         ast_log(LOG_DEBUG, "Hungup, howlong is %d, autologoff is %d\n", howlong, p->autologoff);
775                         if (howlong  && p->autologoff && (howlong > p->autologoff)) {
776                                 char agent[AST_MAX_AGENT] = "";
777                                 long logintime = time(NULL) - p->loginstart;
778                                 p->loginstart = 0;
779                                 ast_log(LOG_NOTICE, "Agent '%s' didn't answer/confirm within %d seconds (waited %d)\n", p->name, p->autologoff, howlong);
780                                 manager_event(EVENT_FLAG_AGENT, "Agentcallbacklogoff",
781                                               "Agent: %s\r\n"
782                                               "Loginchan: %s\r\n"
783                                               "Logintime: %ld\r\n"
784                                               "Reason: Autologoff\r\n"
785                                               "Uniqueid: %s\r\n",
786                                               p->agent, p->loginchan, logintime, ast->uniqueid);
787                                 snprintf(agent, sizeof(agent), "Agent/%s", p->agent);
788                                 ast_queue_log("NONE", ast->uniqueid, agent, "AGENTCALLBACKLOGOFF", "%s|%ld|%s", p->loginchan, logintime, "Autologoff");
789                                 set_agentbycallerid(p->logincallerid, NULL);
790                                 ast_device_state_changed("Agent/%s", p->agent);
791                                 p->loginchan[0] = '\0';
792                                 p->logincallerid[0] = '\0';
793                                 if (persistent_agents)
794                                         dump_agents();
795                         }
796                 } else if (p->dead) {
797                         ast_mutex_lock(&p->chan->lock);
798                         ast_softhangup(p->chan, AST_SOFTHANGUP_EXPLICIT);
799                         ast_mutex_unlock(&p->chan->lock);
800                 } else {
801                         ast_mutex_lock(&p->chan->lock);
802                         ast_moh_start(p->chan, p->moh);
803                         ast_mutex_unlock(&p->chan->lock);
804                 }
805         }
806         ast_mutex_unlock(&p->lock);
807         ast_device_state_changed("Agent/%s", p->agent);
808
809         if (p->pending) {
810                 ast_mutex_lock(&agentlock);
811                 agent_unlink(p);
812                 ast_mutex_unlock(&agentlock);
813         }
814         if (p->abouttograb) {
815                 /* Let the "about to grab" thread know this isn't valid anymore, and let it
816                    kill it later */
817                 p->abouttograb = 0;
818         } else if (p->dead) {
819                 ast_mutex_destroy(&p->lock);
820                 ast_mutex_destroy(&p->app_lock);
821                 free(p);
822         } else {
823                 if (p->chan) {
824                         /* Not dead -- check availability now */
825                         ast_mutex_lock(&p->lock);
826                         /* Store last disconnect time */
827                         p->lastdisc = ast_tvnow();
828                         ast_mutex_unlock(&p->lock);
829                 }
830                 /* Release ownership of the agent to other threads (presumably running the login app). */
831                 ast_mutex_unlock(&p->app_lock);
832         }
833         return 0;
834 }
835
836 static int agent_cont_sleep( void *data )
837 {
838         struct agent_pvt *p;
839         int res;
840
841         p = (struct agent_pvt *)data;
842
843         ast_mutex_lock(&p->lock);
844         res = p->app_sleep_cond;
845         if (p->lastdisc.tv_sec) {
846                 if (ast_tvdiff_ms(ast_tvnow(), p->lastdisc) > p->wrapuptime) 
847                         res = 1;
848         }
849         ast_mutex_unlock(&p->lock);
850 #if 0
851         if( !res )
852                 ast_log( LOG_DEBUG, "agent_cont_sleep() returning %d\n", res );
853 #endif          
854         return res;
855 }
856
857 static int agent_ack_sleep( void *data )
858 {
859         struct agent_pvt *p;
860         int res=0;
861         int to = 1000;
862         struct ast_frame *f;
863
864         /* Wait a second and look for something */
865
866         p = (struct agent_pvt *)data;
867         if (p->chan) {
868                 for(;;) {
869                         to = ast_waitfor(p->chan, to);
870                         if (to < 0) {
871                                 res = -1;
872                                 break;
873                         }
874                         if (!to) {
875                                 res = 0;
876                                 break;
877                         }
878                         f = ast_read(p->chan);
879                         if (!f) {
880                                 res = -1;
881                                 break;
882                         }
883                         if (f->frametype == AST_FRAME_DTMF)
884                                 res = f->subclass;
885                         else
886                                 res = 0;
887                         ast_frfree(f);
888                         ast_mutex_lock(&p->lock);
889                         if (!p->app_sleep_cond) {
890                                 ast_mutex_unlock(&p->lock);
891                                 res = 0;
892                                 break;
893                         } else if (res == '#') {
894                                 ast_mutex_unlock(&p->lock);
895                                 res = 1;
896                                 break;
897                         }
898                         ast_mutex_unlock(&p->lock);
899                         res = 0;
900                 }
901         } else
902                 res = -1;
903         return res;
904 }
905
906 static struct ast_channel *agent_bridgedchannel(struct ast_channel *chan, struct ast_channel *bridge)
907 {
908         struct agent_pvt *p = bridge->tech_pvt;
909         struct ast_channel *ret=NULL;
910
911         if (p) {
912                 if (chan == p->chan)
913                         ret = bridge->_bridge;
914                 else if (chan == bridge->_bridge)
915                         ret = p->chan;
916         }
917
918         if (option_debug)
919                 ast_log(LOG_DEBUG, "Asked for bridged channel on '%s'/'%s', returning '%s'\n", chan->name, bridge->name, ret ? ret->name : "<none>");
920         return ret;
921 }
922
923 /*--- agent_new: Create new agent channel ---*/
924 static struct ast_channel *agent_new(struct agent_pvt *p, int state)
925 {
926         struct ast_channel *tmp;
927         struct ast_frame null_frame = { AST_FRAME_NULL };
928 #if 0
929         if (!p->chan) {
930                 ast_log(LOG_WARNING, "No channel? :(\n");
931                 return NULL;
932         }
933 #endif  
934         tmp = ast_channel_alloc(0);
935         if (tmp) {
936                 tmp->tech = &agent_tech;
937                 if (p->chan) {
938                         tmp->nativeformats = p->chan->nativeformats;
939                         tmp->writeformat = p->chan->writeformat;
940                         tmp->rawwriteformat = p->chan->writeformat;
941                         tmp->readformat = p->chan->readformat;
942                         tmp->rawreadformat = p->chan->readformat;
943                         ast_copy_string(tmp->language, p->chan->language, sizeof(tmp->language));
944                         ast_copy_string(tmp->context, p->chan->context, sizeof(tmp->context));
945                         ast_copy_string(tmp->exten, p->chan->exten, sizeof(tmp->exten));
946                 } else {
947                         tmp->nativeformats = AST_FORMAT_SLINEAR;
948                         tmp->writeformat = AST_FORMAT_SLINEAR;
949                         tmp->rawwriteformat = AST_FORMAT_SLINEAR;
950                         tmp->readformat = AST_FORMAT_SLINEAR;
951                         tmp->rawreadformat = AST_FORMAT_SLINEAR;
952                 }
953                 if (p->pending)
954                         snprintf(tmp->name, sizeof(tmp->name), "Agent/P%s-%d", p->agent, rand() & 0xffff);
955                 else
956                         snprintf(tmp->name, sizeof(tmp->name), "Agent/%s", p->agent);
957                 tmp->type = channeltype;
958                 /* Safe, agentlock already held */
959                 ast_setstate(tmp, state);
960                 tmp->tech_pvt = p;
961                 p->owner = tmp;
962                 ast_mutex_lock(&usecnt_lock);
963                 usecnt++;
964                 ast_mutex_unlock(&usecnt_lock);
965                 ast_update_use_count();
966                 tmp->priority = 1;
967                 /* Wake up and wait for other applications (by definition the login app)
968                  * to release this channel). Takes ownership of the agent channel
969                  * to this thread only.
970                  * For signalling the other thread, ast_queue_frame is used until we
971                  * can safely use signals for this purpose. The pselect() needs to be
972                  * implemented in the kernel for this.
973                  */
974                 p->app_sleep_cond = 0;
975                 if( ast_mutex_trylock(&p->app_lock) )
976                 {
977                         if (p->chan) {
978                                 ast_queue_frame(p->chan, &null_frame);
979                                 ast_mutex_unlock(&p->lock);     /* For other thread to read the condition. */
980                                 ast_mutex_lock(&p->app_lock);
981                                 ast_mutex_lock(&p->lock);
982                         }
983                         if( !p->chan )
984                         {
985                                 ast_log(LOG_WARNING, "Agent disconnected while we were connecting the call\n");
986                                 p->owner = NULL;
987                                 tmp->tech_pvt = NULL;
988                                 p->app_sleep_cond = 1;
989                                 ast_channel_free( tmp );
990                                 ast_mutex_unlock(&p->lock);     /* For other thread to read the condition. */
991                                 ast_mutex_unlock(&p->app_lock);
992                                 return NULL;
993                         }
994                 }
995                 p->owning_app = pthread_self();
996                 /* After the above step, there should not be any blockers. */
997                 if (p->chan) {
998                         if (ast_test_flag(p->chan, AST_FLAG_BLOCKING)) {
999                                 ast_log( LOG_ERROR, "A blocker exists after agent channel ownership acquired\n" );
1000                                 CRASH;
1001                         }
1002                         ast_moh_stop(p->chan);
1003                 }
1004         } else
1005                 ast_log(LOG_WARNING, "Unable to allocate agent channel structure\n");
1006         return tmp;
1007 }
1008
1009
1010 /**
1011  * Read configuration data. The file named agents.conf.
1012  *
1013  * @returns Always 0, or so it seems.
1014  */
1015 static int read_agent_config(void)
1016 {
1017         struct ast_config *cfg;
1018         struct ast_variable *v;
1019         struct agent_pvt *p, *pl, *pn;
1020         char *general_val;
1021
1022         group = 0;
1023         autologoff = 0;
1024         wrapuptime = 0;
1025         ackcall = 0;
1026         cfg = ast_config_load(config);
1027         if (!cfg) {
1028                 ast_log(LOG_NOTICE, "No agent configuration found -- agent support disabled\n");
1029                 return 0;
1030         }
1031         ast_mutex_lock(&agentlock);
1032         p = agents;
1033         while(p) {
1034                 p->dead = 1;
1035                 p = p->next;
1036         }
1037         strcpy(moh, "default");
1038         /* set the default recording values */
1039         recordagentcalls = 0;
1040         createlink = 0;
1041         strcpy(recordformat, "wav");
1042         strcpy(recordformatext, "wav");
1043         urlprefix[0] = '\0';
1044         savecallsin[0] = '\0';
1045
1046         /* Read in [general] section for persistance */
1047         if ((general_val = ast_variable_retrieve(cfg, "general", "persistentagents")))
1048                 persistent_agents = ast_true(general_val);
1049
1050         /* Read in the [agents] section */
1051         v = ast_variable_browse(cfg, "agents");
1052         while(v) {
1053                 /* Create the interface list */
1054                 if (!strcasecmp(v->name, "agent")) {
1055                         add_agent(v->value, 0);
1056                 } else if (!strcasecmp(v->name, "group")) {
1057                         group = ast_get_group(v->value);
1058                 } else if (!strcasecmp(v->name, "autologoff")) {
1059                         autologoff = atoi(v->value);
1060                         if (autologoff < 0)
1061                                 autologoff = 0;
1062                 } else if (!strcasecmp(v->name, "ackcall")) {
1063                         if (!strcasecmp(v->value, "always"))
1064                                 ackcall = 2;
1065                         else if (ast_true(v->value))
1066                                 ackcall = 1;
1067                         else
1068                                 ackcall = 0;
1069                 } else if (!strcasecmp(v->name, "wrapuptime")) {
1070                         wrapuptime = atoi(v->value);
1071                         if (wrapuptime < 0)
1072                                 wrapuptime = 0;
1073                 } else if (!strcasecmp(v->name, "maxlogintries") && !ast_strlen_zero(v->value)) {
1074                         maxlogintries = atoi(v->value);
1075                         if (maxlogintries < 0)
1076                                 maxlogintries = 0;
1077                 } else if (!strcasecmp(v->name, "goodbye") && !ast_strlen_zero(v->value)) {
1078                         strcpy(agentgoodbye,v->value);
1079                 } else if (!strcasecmp(v->name, "musiconhold")) {
1080                         ast_copy_string(moh, v->value, sizeof(moh));
1081                 } else if (!strcasecmp(v->name, "updatecdr")) {
1082                         if (ast_true(v->value))
1083                                 updatecdr = 1;
1084                         else
1085                                 updatecdr = 0;
1086                 } else if (!strcasecmp(v->name, "recordagentcalls")) {
1087                         recordagentcalls = ast_true(v->value);
1088                 } else if (!strcasecmp(v->name, "createlink")) {
1089                         createlink = ast_true(v->value);
1090                 } else if (!strcasecmp(v->name, "recordformat")) {
1091                         ast_copy_string(recordformat, v->value, sizeof(recordformat));
1092                         if (!strcasecmp(v->value, "wav49"))
1093                                 strcpy(recordformatext, "WAV");
1094                         else
1095                                 ast_copy_string(recordformatext, v->value, sizeof(recordformatext));
1096                 } else if (!strcasecmp(v->name, "urlprefix")) {
1097                         ast_copy_string(urlprefix, v->value, sizeof(urlprefix));
1098                         if (urlprefix[strlen(urlprefix) - 1] != '/')
1099                                 strncat(urlprefix, "/", sizeof(urlprefix) - strlen(urlprefix) - 1);
1100                 } else if (!strcasecmp(v->name, "savecallsin")) {
1101                         if (v->value[0] == '/')
1102                                 ast_copy_string(savecallsin, v->value, sizeof(savecallsin));
1103                         else
1104                                 snprintf(savecallsin, sizeof(savecallsin) - 2, "/%s", v->value);
1105                         if (savecallsin[strlen(savecallsin) - 1] != '/')
1106                                 strncat(savecallsin, "/", sizeof(savecallsin) - strlen(savecallsin) - 1);
1107                 } else if (!strcasecmp(v->name, "custom_beep")) {
1108                         ast_copy_string(beep, v->value, sizeof(beep));
1109                 }
1110                 v = v->next;
1111         }
1112         p = agents;
1113         pl = NULL;
1114         while(p) {
1115                 pn = p->next;
1116                 if (p->dead) {
1117                         /* Unlink */
1118                         if (pl)
1119                                 pl->next = p->next;
1120                         else
1121                                 agents = p->next;
1122                         /* Destroy if  appropriate */
1123                         if (!p->owner) {
1124                                 if (!p->chan) {
1125                                         ast_mutex_destroy(&p->lock);
1126                                         ast_mutex_destroy(&p->app_lock);
1127                                         free(p);
1128                                 } else {
1129                                         /* Cause them to hang up */
1130                                         ast_softhangup(p->chan, AST_SOFTHANGUP_EXPLICIT);
1131                                 }
1132                         }
1133                 } else
1134                         pl = p;
1135                 p = pn;
1136         }
1137         ast_mutex_unlock(&agentlock);
1138         ast_config_destroy(cfg);
1139         return 0;
1140 }
1141
1142 static int check_availability(struct agent_pvt *newlyavailable, int needlock)
1143 {
1144         struct ast_channel *chan=NULL, *parent=NULL;
1145         struct agent_pvt *p;
1146         int res;
1147
1148         if (option_debug)
1149                 ast_log(LOG_DEBUG, "Checking availability of '%s'\n", newlyavailable->agent);
1150         if (needlock)
1151                 ast_mutex_lock(&agentlock);
1152         p = agents;
1153         while(p) {
1154                 if (p == newlyavailable) {
1155                         p = p->next;
1156                         continue;
1157                 }
1158                 ast_mutex_lock(&p->lock);
1159                 if (!p->abouttograb && p->pending && ((p->group && (newlyavailable->group & p->group)) || !strcmp(p->agent, newlyavailable->agent))) {
1160                         if (option_debug)
1161                                 ast_log(LOG_DEBUG, "Call '%s' looks like a winner for agent '%s'\n", p->owner->name, newlyavailable->agent);
1162                         /* We found a pending call, time to merge */
1163                         chan = agent_new(newlyavailable, AST_STATE_DOWN);
1164                         parent = p->owner;
1165                         p->abouttograb = 1;
1166                         ast_mutex_unlock(&p->lock);
1167                         break;
1168                 }
1169                 ast_mutex_unlock(&p->lock);
1170                 p = p->next;
1171         }
1172         if (needlock)
1173                 ast_mutex_unlock(&agentlock);
1174         if (parent && chan)  {
1175                 if (newlyavailable->ackcall > 1) {
1176                         /* Don't do beep here */
1177                         res = 0;
1178                 } else {
1179                         if (option_debug > 2)
1180                                 ast_log( LOG_DEBUG, "Playing beep, lang '%s'\n", newlyavailable->chan->language);
1181                         res = ast_streamfile(newlyavailable->chan, beep, newlyavailable->chan->language);
1182                         if (option_debug > 2)
1183                                 ast_log( LOG_DEBUG, "Played beep, result '%d'\n", res);
1184                         if (!res) {
1185                                 res = ast_waitstream(newlyavailable->chan, "");
1186                                 ast_log( LOG_DEBUG, "Waited for stream, result '%d'\n", res);
1187                         }
1188                 }
1189                 if (!res) {
1190                         /* Note -- parent may have disappeared */
1191                         if (p->abouttograb) {
1192                                 newlyavailable->acknowledged = 1;
1193                                 /* Safe -- agent lock already held */
1194                                 ast_setstate(parent, AST_STATE_UP);
1195                                 ast_setstate(chan, AST_STATE_UP);
1196                                 ast_copy_string(parent->context, chan->context, sizeof(parent->context));
1197                                 /* Go ahead and mark the channel as a zombie so that masquerade will
1198                                    destroy it for us, and we need not call ast_hangup */
1199                                 ast_mutex_lock(&parent->lock);
1200                                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1201                                 ast_channel_masquerade(parent, chan);
1202                                 ast_mutex_unlock(&parent->lock);
1203                                 p->abouttograb = 0;
1204                         } else {
1205                                 if (option_debug)
1206                                         ast_log(LOG_DEBUG, "Sneaky, parent disappeared in the mean time...\n");
1207                                 agent_cleanup(newlyavailable);
1208                         }
1209                 } else {
1210                         if (option_debug)
1211                                 ast_log(LOG_DEBUG, "Ugh...  Agent hung up at exactly the wrong time\n");
1212                         agent_cleanup(newlyavailable);
1213                 }
1214         }
1215         return 0;
1216 }
1217
1218 static int check_beep(struct agent_pvt *newlyavailable, int needlock)
1219 {
1220         struct agent_pvt *p;
1221         int res=0;
1222
1223         ast_log(LOG_DEBUG, "Checking beep availability of '%s'\n", newlyavailable->agent);
1224         if (needlock)
1225                 ast_mutex_lock(&agentlock);
1226         p = agents;
1227         while(p) {
1228                 if (p == newlyavailable) {
1229                         p = p->next;
1230                         continue;
1231                 }
1232                 ast_mutex_lock(&p->lock);
1233                 if (!p->abouttograb && p->pending && ((p->group && (newlyavailable->group & p->group)) || !strcmp(p->agent, newlyavailable->agent))) {
1234                         if (option_debug)
1235                                 ast_log(LOG_DEBUG, "Call '%s' looks like a would-be winner for agent '%s'\n", p->owner->name, newlyavailable->agent);
1236                         ast_mutex_unlock(&p->lock);
1237                         break;
1238                 }
1239                 ast_mutex_unlock(&p->lock);
1240                 p = p->next;
1241         }
1242         if (needlock)
1243                 ast_mutex_unlock(&agentlock);
1244         if (p) {
1245                 ast_mutex_unlock(&newlyavailable->lock);
1246                 if (option_debug > 2)
1247                         ast_log( LOG_DEBUG, "Playing beep, lang '%s'\n", newlyavailable->chan->language);
1248                 res = ast_streamfile(newlyavailable->chan, beep, newlyavailable->chan->language);
1249                 if (option_debug > 2)
1250                         ast_log( LOG_DEBUG, "Played beep, result '%d'\n", res);
1251                 if (!res) {
1252                         res = ast_waitstream(newlyavailable->chan, "");
1253                         if (option_debug)
1254                                 ast_log( LOG_DEBUG, "Waited for stream, result '%d'\n", res);
1255                 }
1256                 ast_mutex_lock(&newlyavailable->lock);
1257         }
1258         return res;
1259 }
1260
1261 /*--- agent_request: Part of the Asterisk PBX interface ---*/
1262 static struct ast_channel *agent_request(const char *type, int format, void *data, int *cause)
1263 {
1264         struct agent_pvt *p;
1265         struct ast_channel *chan = NULL;
1266         char *s;
1267         ast_group_t groupmatch;
1268         int groupoff;
1269         int waitforagent=0;
1270         int hasagent = 0;
1271         struct timeval tv;
1272
1273         s = data;
1274         if ((s[0] == '@') && (sscanf(s + 1, "%d", &groupoff) == 1)) {
1275                 groupmatch = (1 << groupoff);
1276         } else if ((s[0] == ':') && (sscanf(s + 1, "%d", &groupoff) == 1)) {
1277                 groupmatch = (1 << groupoff);
1278                 waitforagent = 1;
1279         } else {
1280                 groupmatch = 0;
1281         }
1282
1283         /* Check actual logged in agents first */
1284         ast_mutex_lock(&agentlock);
1285         p = agents;
1286         while(p) {
1287                 ast_mutex_lock(&p->lock);
1288                 if (!p->pending && ((groupmatch && (p->group & groupmatch)) || !strcmp(data, p->agent)) &&
1289                     ast_strlen_zero(p->loginchan)) {
1290                         if (p->chan)
1291                                 hasagent++;
1292                         if (!p->lastdisc.tv_sec) {
1293                                 /* Agent must be registered, but not have any active call, and not be in a waiting state */
1294                                 if (!p->owner && p->chan) {
1295                                         /* Fixed agent */
1296                                         chan = agent_new(p, AST_STATE_DOWN);
1297                                 }
1298                                 if (chan) {
1299                                         ast_mutex_unlock(&p->lock);
1300                                         break;
1301                                 }
1302                         }
1303                 }
1304                 ast_mutex_unlock(&p->lock);
1305                 p = p->next;
1306         }
1307         if (!p) {
1308                 p = agents;
1309                 while(p) {
1310                         ast_mutex_lock(&p->lock);
1311                         if (!p->pending && ((groupmatch && (p->group & groupmatch)) || !strcmp(data, p->agent))) {
1312                                 if (p->chan || !ast_strlen_zero(p->loginchan))
1313                                         hasagent++;
1314                                 tv = ast_tvnow();
1315 #if 0
1316                                 ast_log(LOG_NOTICE, "Time now: %ld, Time of lastdisc: %ld\n", tv.tv_sec, p->lastdisc.tv_sec);
1317 #endif
1318                                 if (!p->lastdisc.tv_sec || (tv.tv_sec > p->lastdisc.tv_sec)) {
1319                                         p->lastdisc = ast_tv(0, 0);
1320                                         /* Agent must be registered, but not have any active call, and not be in a waiting state */
1321                                         if (!p->owner && p->chan) {
1322                                                 /* Could still get a fixed agent */
1323                                                 chan = agent_new(p, AST_STATE_DOWN);
1324                                         } else if (!p->owner && !ast_strlen_zero(p->loginchan)) {
1325                                                 /* Adjustable agent */
1326                                                 p->chan = ast_request("Local", format, p->loginchan, cause);
1327                                                 if (p->chan)
1328                                                         chan = agent_new(p, AST_STATE_DOWN);
1329                                         }
1330                                         if (chan) {
1331                                                 ast_mutex_unlock(&p->lock);
1332                                                 break;
1333                                         }
1334                                 }
1335                         }
1336                         ast_mutex_unlock(&p->lock);
1337                         p = p->next;
1338                 }
1339         }
1340
1341         if (!chan && waitforagent) {
1342                 /* No agent available -- but we're requesting to wait for one.
1343                    Allocate a place holder */
1344                 if (hasagent) {
1345                         if (option_debug)
1346                                 ast_log(LOG_DEBUG, "Creating place holder for '%s'\n", s);
1347                         p = add_agent(data, 1);
1348                         p->group = groupmatch;
1349                         chan = agent_new(p, AST_STATE_DOWN);
1350                         if (!chan) {
1351                                 ast_log(LOG_WARNING, "Weird...  Fix this to drop the unused pending agent\n");
1352                         }
1353                 } else
1354                         ast_log(LOG_DEBUG, "Not creating place holder for '%s' since nobody logged in\n", s);
1355         }
1356         if (hasagent)
1357                 *cause = AST_CAUSE_BUSY;
1358         else
1359                 *cause = AST_CAUSE_UNREGISTERED;
1360         ast_mutex_unlock(&agentlock);
1361         return chan;
1362 }
1363
1364 static int powerof(unsigned int v)
1365 {
1366         int x;
1367         for (x=0;x<32;x++) {
1368                 if (v & (1 << x)) return x;
1369         }
1370         return 0;
1371 }
1372
1373 /**
1374  * Lists agents and their status to the Manager API.
1375  * It is registered on load_module() and it gets called by the manager backend.
1376  * @param s
1377  * @param m
1378  * @returns 
1379  * @sa action_agent_logoff(), action_agent_callback_login(), load_module().
1380  */
1381 static int action_agents(struct mansession *s, struct message *m)
1382 {
1383         char *id = astman_get_header(m,"ActionID");
1384         char idText[256] = "";
1385         char chanbuf[256];
1386         struct agent_pvt *p;
1387         char *username = NULL;
1388         char *loginChan = NULL;
1389         char *talkingtoChan = NULL;
1390         char *status = NULL;
1391
1392         if (!ast_strlen_zero(id))
1393                 snprintf(idText, sizeof(idText) ,"ActionID: %s\r\n", id);
1394         astman_send_ack(s, m, "Agents will follow");
1395         ast_mutex_lock(&agentlock);
1396         p = agents;
1397         while(p) {
1398                 ast_mutex_lock(&p->lock);
1399
1400                 /* Status Values:
1401                    AGENT_LOGGEDOFF - Agent isn't logged in
1402                    AGENT_IDLE      - Agent is logged in, and waiting for call
1403                    AGENT_ONCALL    - Agent is logged in, and on a call
1404                    AGENT_UNKNOWN   - Don't know anything about agent. Shouldn't ever get this. */
1405
1406                 if(!ast_strlen_zero(p->name)) {
1407                         username = p->name;
1408                 } else {
1409                         username = "None";
1410                 }
1411
1412                 /* Set a default status. It 'should' get changed. */
1413                 status = "AGENT_UNKNOWN";
1414
1415                 if (!ast_strlen_zero(p->loginchan) && !p->chan) {
1416                         loginChan = p->loginchan;
1417                         talkingtoChan = "n/a";
1418                         status = "AGENT_IDLE";
1419                         if (p->acknowledged) {
1420                                 snprintf(chanbuf, sizeof(chanbuf), " %s (Confirmed)", p->loginchan);
1421                                 loginChan = chanbuf;
1422                         }
1423                 } else if (p->chan) {
1424                         loginChan = ast_strdupa(p->chan->name);
1425                         if (p->owner && p->owner->_bridge) {
1426                                 talkingtoChan = p->chan->cid.cid_num;
1427                                 status = "AGENT_ONCALL";
1428                         } else {
1429                                 talkingtoChan = "n/a";
1430                                 status = "AGENT_IDLE";
1431                         }
1432                 } else {
1433                         loginChan = "n/a";
1434                         talkingtoChan = "n/a";
1435                         status = "AGENT_LOGGEDOFF";
1436                 }
1437
1438                 ast_cli(s->fd, "Event: Agents\r\n"
1439                         "Agent: %s\r\n"
1440                         "Name: %s\r\n"
1441                         "Status: %s\r\n"
1442                         "LoggedInChan: %s\r\n"
1443                         "LoggedInTime: %d\r\n"
1444                         "TalkingTo: %s\r\n"
1445                         "%s"
1446                         "\r\n",
1447                         p->agent, username, status, loginChan, (int)p->loginstart, talkingtoChan, idText);
1448                 ast_mutex_unlock(&p->lock);
1449                 p = p->next;
1450         }
1451         ast_mutex_unlock(&agentlock);
1452         ast_cli(s->fd, "Event: AgentsComplete\r\n"
1453                 "%s"
1454                 "\r\n",idText);
1455         return 0;
1456 }
1457
1458 static int agent_logoff(char *agent, int soft)
1459 {
1460         struct agent_pvt *p;
1461         long logintime;
1462         int ret = -1; /* Return -1 if no agent if found */
1463
1464         for (p=agents; p; p=p->next) {
1465                 if (!strcasecmp(p->agent, agent)) {
1466                         if (!soft) {
1467                                 if (p->owner) {
1468                                         ast_softhangup(p->owner, AST_SOFTHANGUP_EXPLICIT);
1469                                 }
1470                                 if (p->chan) {
1471                                         ast_softhangup(p->chan, AST_SOFTHANGUP_EXPLICIT);
1472                                 }
1473                         }
1474                         ret = 0; /* found an agent => return 0 */
1475                         logintime = time(NULL) - p->loginstart;
1476                         p->loginstart = 0;
1477                         
1478                         manager_event(EVENT_FLAG_AGENT, "Agentcallbacklogoff",
1479                                       "Agent: %s\r\n"
1480                                       "Loginchan: %s\r\n"
1481                                       "Logintime: %ld\r\n",
1482                                       p->agent, p->loginchan, logintime);
1483                         ast_queue_log("NONE", "NONE", agent, "AGENTCALLBACKLOGOFF", "%s|%ld|%s", p->loginchan, logintime, "CommandLogoff");
1484                         set_agentbycallerid(p->logincallerid, NULL);
1485                         p->loginchan[0] = '\0';
1486                         p->logincallerid[0] = '\0';
1487                         ast_device_state_changed("Agent/%s", p->agent);
1488                         if (persistent_agents)
1489                                 dump_agents();
1490                         break;
1491                 }
1492         }
1493
1494         return ret;
1495 }
1496
1497 static int agent_logoff_cmd(int fd, int argc, char **argv)
1498 {
1499         int ret;
1500         char *agent;
1501
1502         if (argc < 3 || argc > 4)
1503                 return RESULT_SHOWUSAGE;
1504         if (argc == 4 && strcasecmp(argv[3], "soft"))
1505                 return RESULT_SHOWUSAGE;
1506
1507         agent = argv[2] + 6;
1508         ret = agent_logoff(agent, argc == 4);
1509         if (ret == 0)
1510                 ast_cli(fd, "Logging out %s\n", agent);
1511
1512         return RESULT_SUCCESS;
1513 }
1514
1515 /**
1516  * Sets an agent as no longer logged in in the Manager API.
1517  * It is registered on load_module() and it gets called by the manager backend.
1518  * @param s
1519  * @param m
1520  * @returns 
1521  * @sa action_agents(), action_agent_callback_login(), load_module().
1522  */
1523 static int action_agent_logoff(struct mansession *s, struct message *m)
1524 {
1525         char *agent = astman_get_header(m, "Agent");
1526         char *soft_s = astman_get_header(m, "Soft"); /* "true" is don't hangup */
1527         int soft;
1528         int ret; /* return value of agent_logoff */
1529
1530         if (ast_strlen_zero(agent)) {
1531                 astman_send_error(s, m, "No agent specified");
1532                 return 0;
1533         }
1534
1535         if (ast_true(soft_s))
1536                 soft = 1;
1537         else
1538                 soft = 0;
1539
1540         ret = agent_logoff(agent, soft);
1541         if (ret == 0)
1542                 astman_send_ack(s, m, "Agent logged out");
1543         else
1544                 astman_send_error(s, m, "No such agent");
1545
1546         return 0;
1547 }
1548
1549 static char *complete_agent_logoff_cmd(char *line, char *word, int pos, int state)
1550 {
1551         struct agent_pvt *p;
1552         char name[AST_MAX_AGENT];
1553         int which = 0;
1554
1555         if (pos == 2) {
1556                 for (p=agents; p; p=p->next) {
1557                         snprintf(name, sizeof(name), "Agent/%s", p->agent);
1558                         if (!strncasecmp(word, name, strlen(word))) {
1559                                 if (++which > state) {
1560                                         return ast_strdup(name);
1561                                 }
1562                         }
1563                 }
1564         } else if (pos == 3 && state == 0) {
1565                 return ast_strdup("soft");
1566         }
1567         return NULL;
1568 }
1569
1570 /**
1571  * Show agents in cli.
1572  */
1573 static int agents_show(int fd, int argc, char **argv)
1574 {
1575         struct agent_pvt *p;
1576         char username[AST_MAX_BUF];
1577         char location[AST_MAX_BUF] = "";
1578         char talkingto[AST_MAX_BUF] = "";
1579         char moh[AST_MAX_BUF];
1580         int count_agents = 0;           /* Number of agents configured */
1581         int online_agents = 0;          /* Number of online agents */
1582         int offline_agents = 0;         /* Number of offline agents */
1583         if (argc != 2)
1584                 return RESULT_SHOWUSAGE;
1585         ast_mutex_lock(&agentlock);
1586         p = agents;
1587         while(p) {
1588                 ast_mutex_lock(&p->lock);
1589                 if (p->pending) {
1590                         if (p->group)
1591                                 ast_cli(fd, "-- Pending call to group %d\n", powerof(p->group));
1592                         else
1593                                 ast_cli(fd, "-- Pending call to agent %s\n", p->agent);
1594                 } else {
1595                         if (!ast_strlen_zero(p->name))
1596                                 snprintf(username, sizeof(username), "(%s) ", p->name);
1597                         else
1598                                 username[0] = '\0';
1599                         if (p->chan) {
1600                                 snprintf(location, sizeof(location), "logged in on %s", p->chan->name);
1601                                 if (p->owner && ast_bridged_channel(p->owner)) {
1602                                         snprintf(talkingto, sizeof(talkingto), " talking to %s", ast_bridged_channel(p->owner)->name);
1603                                 } else {
1604                                         strcpy(talkingto, " is idle");
1605                                 }
1606                                 online_agents++;
1607                         } else if (!ast_strlen_zero(p->loginchan)) {
1608                                 snprintf(location, sizeof(location) - 20, "available at '%s'", p->loginchan);
1609                                 talkingto[0] = '\0';
1610                                 online_agents++;
1611                                 if (p->acknowledged)
1612                                         strncat(location, " (Confirmed)", sizeof(location) - strlen(location) - 1);
1613                         } else {
1614                                 strcpy(location, "not logged in");
1615                                 talkingto[0] = '\0';
1616                                 offline_agents++;
1617                         }
1618                         if (!ast_strlen_zero(p->moh))
1619                                 snprintf(moh, sizeof(moh), " (musiconhold is '%s')", p->moh);
1620                         ast_cli(fd, "%-12.12s %s%s%s%s\n", p->agent, 
1621                                 username, location, talkingto, moh);
1622                         count_agents++;
1623                 }
1624                 ast_mutex_unlock(&p->lock);
1625                 p = p->next;
1626         }
1627         ast_mutex_unlock(&agentlock);
1628         if ( !count_agents ) {
1629                 ast_cli(fd, "No Agents are configured in %s\n",config);
1630         } else {
1631                 ast_cli(fd, "%d agents configured [%d online , %d offline]\n",count_agents, online_agents, offline_agents);
1632         }
1633         ast_cli(fd, "\n");
1634                         
1635         return RESULT_SUCCESS;
1636 }
1637
1638 static char show_agents_usage[] = 
1639 "Usage: show agents\n"
1640 "       Provides summary information on agents.\n";
1641
1642 static char agent_logoff_usage[] =
1643 "Usage: agent logoff <channel> [soft]\n"
1644 "       Sets an agent as no longer logged in.\n"
1645 "       If 'soft' is specified, do not hangup existing calls.\n";
1646
1647 static struct ast_cli_entry cli_show_agents = {
1648         { "show", "agents", NULL }, agents_show, 
1649         "Show status of agents", show_agents_usage, NULL };
1650
1651 static struct ast_cli_entry cli_agent_logoff = {
1652         { "agent", "logoff", NULL }, agent_logoff_cmd, 
1653         "Sets an agent offline", agent_logoff_usage, complete_agent_logoff_cmd };
1654
1655 STANDARD_LOCAL_USER;
1656 LOCAL_USER_DECL;
1657
1658 /*!
1659  * \brief Log in agent application.
1660  *
1661  * \param chan
1662  * \param data
1663  * \param callbackmode non-zero for AgentCallbackLogin
1664  */
1665 static int __login_exec(struct ast_channel *chan, void *data, int callbackmode)
1666 {
1667         int res=0;
1668         int tries = 0;
1669         int max_login_tries = maxlogintries;
1670         struct agent_pvt *p;
1671         struct localuser *u;
1672         int login_state = 0;
1673         char user[AST_MAX_AGENT] = "";
1674         char pass[AST_MAX_AGENT];
1675         char agent[AST_MAX_AGENT] = "";
1676         char xpass[AST_MAX_AGENT] = "";
1677         char *errmsg;
1678         char *parse;
1679         AST_DECLARE_APP_ARGS(args,
1680                              AST_APP_ARG(agent_id);
1681                              AST_APP_ARG(options);
1682                              AST_APP_ARG(extension);
1683                 );
1684         const char *tmpoptions = NULL;
1685         char *context = NULL;
1686         int play_announcement = 1;
1687         char agent_goodbye[AST_MAX_FILENAME_LEN];
1688         int update_cdr = updatecdr;
1689         char *filename = "agent-loginok";
1690         char tmpchan[AST_MAX_BUF] = "";
1691
1692         LOCAL_USER_ADD(u);
1693
1694         if (!(parse = ast_strdupa(data))) {
1695                 ast_log(LOG_ERROR, "Out of memory!\n");
1696                 LOCAL_USER_REMOVE(u);
1697                 return -1;
1698         }
1699
1700         AST_STANDARD_APP_ARGS(args, parse);
1701
1702         ast_copy_string(agent_goodbye, agentgoodbye, sizeof(agent_goodbye));
1703
1704         /* Set Channel Specific Login Overrides */
1705         if (pbx_builtin_getvar_helper(chan, "AGENTLMAXLOGINTRIES") && strlen(pbx_builtin_getvar_helper(chan, "AGENTLMAXLOGINTRIES"))) {
1706                 max_login_tries = atoi(pbx_builtin_getvar_helper(chan, "AGENTMAXLOGINTRIES"));
1707                 if (max_login_tries < 0)
1708                         max_login_tries = 0;
1709                 tmpoptions=pbx_builtin_getvar_helper(chan, "AGENTMAXLOGINTRIES");
1710                 if (option_verbose > 2)
1711                         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);
1712         }
1713         if (pbx_builtin_getvar_helper(chan, "AGENTUPDATECDR") && !ast_strlen_zero(pbx_builtin_getvar_helper(chan, "AGENTUPDATECDR"))) {
1714                 if (ast_true(pbx_builtin_getvar_helper(chan, "AGENTUPDATECDR")))
1715                         update_cdr = 1;
1716                 else
1717                         update_cdr = 0;
1718                 tmpoptions=pbx_builtin_getvar_helper(chan, "AGENTUPDATECDR");
1719                 if (option_verbose > 2)
1720                         ast_verbose(VERBOSE_PREFIX_3 "Saw variable AGENTUPDATECDR=%s, setting update_cdr to: %d on Channel '%s'.\n",tmpoptions,update_cdr,chan->name);
1721         }
1722         if (pbx_builtin_getvar_helper(chan, "AGENTGOODBYE") && !ast_strlen_zero(pbx_builtin_getvar_helper(chan, "AGENTGOODBYE"))) {
1723                 strcpy(agent_goodbye, pbx_builtin_getvar_helper(chan, "AGENTGOODBYE"));
1724                 tmpoptions=pbx_builtin_getvar_helper(chan, "AGENTGOODBYE");
1725                 if (option_verbose > 2)
1726                         ast_verbose(VERBOSE_PREFIX_3 "Saw variable AGENTGOODBYE=%s, setting agent_goodbye to: %s on Channel '%s'.\n",tmpoptions,agent_goodbye,chan->name);
1727         }
1728         /* End Channel Specific Login Overrides */
1729         
1730         if (callbackmode && args.extension) {
1731                 parse = args.extension;
1732                 args.extension = strsep(&parse, "@");
1733                 context = parse;
1734         }
1735
1736         if (!ast_strlen_zero(args.options)) {
1737                 if (strchr(args.options, 's')) {
1738                         play_announcement = 0;
1739                 }
1740         }
1741
1742         if (chan->_state != AST_STATE_UP)
1743                 res = ast_answer(chan);
1744         if (!res) {
1745                 if (!ast_strlen_zero(args.agent_id))
1746                         ast_copy_string(user, args.agent_id, AST_MAX_AGENT);
1747                 else
1748                         res = ast_app_getdata(chan, "agent-user", user, sizeof(user) - 1, 0);
1749         }
1750         while (!res && (max_login_tries==0 || tries < max_login_tries)) {
1751                 tries++;
1752                 /* Check for password */
1753                 ast_mutex_lock(&agentlock);
1754                 p = agents;
1755                 while(p) {
1756                         if (!strcmp(p->agent, user) && !p->pending)
1757                                 ast_copy_string(xpass, p->password, sizeof(xpass));
1758                         p = p->next;
1759                 }
1760                 ast_mutex_unlock(&agentlock);
1761                 if (!res) {
1762                         if (!ast_strlen_zero(xpass))
1763                                 res = ast_app_getdata(chan, "agent-pass", pass, sizeof(pass) - 1, 0);
1764                         else
1765                                 pass[0] = '\0';
1766                 }
1767                 errmsg = "agent-incorrect";
1768
1769 #if 0
1770                 ast_log(LOG_NOTICE, "user: %s, pass: %s\n", user, pass);
1771 #endif          
1772
1773                 /* Check again for accuracy */
1774                 ast_mutex_lock(&agentlock);
1775                 p = agents;
1776                 while(p) {
1777                         ast_mutex_lock(&p->lock);
1778                         if (!strcmp(p->agent, user) &&
1779                             !strcmp(p->password, pass) && !p->pending) {
1780                                 login_state = 1; /* Successful Login */
1781
1782                                 /* Ensure we can't be gotten until we're done */
1783                                 gettimeofday(&p->lastdisc, NULL);
1784                                 p->lastdisc.tv_sec++;
1785
1786                                 /* Set Channel Specific Agent Overides */
1787                                 if (pbx_builtin_getvar_helper(chan, "AGENTACKCALL") && strlen(pbx_builtin_getvar_helper(chan, "AGENTACKCALL"))) {
1788                                         if (!strcasecmp(pbx_builtin_getvar_helper(chan, "AGENTACKCALL"), "always"))
1789                                                 p->ackcall = 2;
1790                                         else if (ast_true(pbx_builtin_getvar_helper(chan, "AGENTACKCALL")))
1791                                                 p->ackcall = 1;
1792                                         else
1793                                                 p->ackcall = 0;
1794                                         tmpoptions=pbx_builtin_getvar_helper(chan, "AGENTACKCALL");
1795                                         if (option_verbose > 2)
1796                                                 ast_verbose(VERBOSE_PREFIX_3 "Saw variable AGENTACKCALL=%s, setting ackcall to: %d for Agent '%s'.\n",tmpoptions,p->ackcall,p->agent);
1797                                 }
1798                                 if (pbx_builtin_getvar_helper(chan, "AGENTAUTOLOGOFF") && strlen(pbx_builtin_getvar_helper(chan, "AGENTAUTOLOGOFF"))) {
1799                                         p->autologoff = atoi(pbx_builtin_getvar_helper(chan, "AGENTAUTOLOGOFF"));
1800                                         if (p->autologoff < 0)
1801                                                 p->autologoff = 0;
1802                                         tmpoptions=pbx_builtin_getvar_helper(chan, "AGENTAUTOLOGOFF");
1803                                         if (option_verbose > 2)
1804                                                 ast_verbose(VERBOSE_PREFIX_3 "Saw variable AGENTAUTOLOGOFF=%s, setting autologff to: %d for Agent '%s'.\n",tmpoptions,p->autologoff,p->agent);
1805                                 }
1806                                 if (pbx_builtin_getvar_helper(chan, "AGENTWRAPUPTIME") && strlen(pbx_builtin_getvar_helper(chan, "AGENTWRAPUPTIME"))) {
1807                                         p->wrapuptime = atoi(pbx_builtin_getvar_helper(chan, "AGENTWRAPUPTIME"));
1808                                         if (p->wrapuptime < 0)
1809                                                 p->wrapuptime = 0;
1810                                         tmpoptions=pbx_builtin_getvar_helper(chan, "AGENTWRAPUPTIME");
1811                                         if (option_verbose > 2)
1812                                                 ast_verbose(VERBOSE_PREFIX_3 "Saw variable AGENTWRAPUPTIME=%s, setting wrapuptime to: %d for Agent '%s'.\n",tmpoptions,p->wrapuptime,p->agent);
1813                                 }
1814                                 /* End Channel Specific Agent Overides */
1815                                 if (!p->chan) {
1816                                         char last_loginchan[80] = "";
1817                                         long logintime;
1818                                         snprintf(agent, sizeof(agent), "Agent/%s", p->agent);
1819
1820                                         if (callbackmode) {
1821                                                 int pos = 0;
1822                                                 /* Retrieve login chan */
1823                                                 for (;;) {
1824                                                         if (!ast_strlen_zero(args.extension)) {
1825                                                                 ast_copy_string(tmpchan, args.extension, sizeof(tmpchan));
1826                                                                 res = 0;
1827                                                         } else
1828                                                                 res = ast_app_getdata(chan, "agent-newlocation", tmpchan+pos, sizeof(tmpchan) - 2, 0);
1829                                                         if (ast_strlen_zero(tmpchan) || ast_exists_extension(chan, !ast_strlen_zero(context) ? context : "default", tmpchan,
1830                                                                                                              1, NULL))
1831                                                                 break;
1832                                                         if (args.extension) {
1833                                                                 ast_log(LOG_WARNING, "Extension '%s' is not valid for automatic login of agent '%s'\n", args.extension, p->agent);
1834                                                                 args.extension = NULL;
1835                                                                 pos = 0;
1836                                                         } else {
1837                                                                 ast_log(LOG_WARNING, "Extension '%s@%s' is not valid for automatic login of agent '%s'\n", tmpchan, !ast_strlen_zero(context) ? context : "default", p->agent);
1838                                                                 res = ast_streamfile(chan, "invalid", chan->language);
1839                                                                 if (!res)
1840                                                                         res = ast_waitstream(chan, AST_DIGIT_ANY);
1841                                                                 if (res > 0) {
1842                                                                         tmpchan[0] = res;
1843                                                                         tmpchan[1] = '\0';
1844                                                                         pos = 1;
1845                                                                 } else {
1846                                                                         tmpchan[0] = '\0';
1847                                                                         pos = 0;
1848                                                                 }
1849                                                         }
1850                                                 }
1851                                                 args.extension = tmpchan;
1852                                                 if (!res) {
1853                                                         set_agentbycallerid(p->logincallerid, NULL);
1854                                                         if (!ast_strlen_zero(context) && !ast_strlen_zero(tmpchan))
1855                                                                 snprintf(p->loginchan, sizeof(p->loginchan), "%s@%s", tmpchan, context);
1856                                                         else {
1857                                                                 ast_copy_string(last_loginchan, p->loginchan, sizeof(last_loginchan));
1858                                                                 ast_copy_string(p->loginchan, tmpchan, sizeof(p->loginchan));
1859                                                         }
1860                                                         p->acknowledged = 0;
1861                                                         if (ast_strlen_zero(p->loginchan)) {
1862                                                                 login_state = 2;
1863                                                                 filename = "agent-loggedoff";
1864                                                         } else {
1865                                                                 if (chan->cid.cid_num) {
1866                                                                         ast_copy_string(p->logincallerid, chan->cid.cid_num, sizeof(p->logincallerid));
1867                                                                         set_agentbycallerid(p->logincallerid, p->agent);
1868                                                                 } else
1869                                                                         p->logincallerid[0] = '\0';
1870                                                         }
1871
1872                                                         if(update_cdr && chan->cdr)
1873                                                                 snprintf(chan->cdr->channel, sizeof(chan->cdr->channel), "Agent/%s", p->agent);
1874
1875                                                 }
1876                                         } else {
1877                                                 p->loginchan[0] = '\0';
1878                                                 p->logincallerid[0] = '\0';
1879                                                 p->acknowledged = 0;
1880                                         }
1881                                         ast_mutex_unlock(&p->lock);
1882                                         ast_mutex_unlock(&agentlock);
1883                                         if( !res && play_announcement==1 )
1884                                                 res = ast_streamfile(chan, filename, chan->language);
1885                                         if (!res)
1886                                                 ast_waitstream(chan, "");
1887                                         ast_mutex_lock(&agentlock);
1888                                         ast_mutex_lock(&p->lock);
1889                                         if (!res) {
1890                                                 res = ast_set_read_format(chan, ast_best_codec(chan->nativeformats));
1891                                                 if (res)
1892                                                         ast_log(LOG_WARNING, "Unable to set read format to %d\n", ast_best_codec(chan->nativeformats));
1893                                         }
1894                                         if (!res) {
1895                                                 res = ast_set_write_format(chan, ast_best_codec(chan->nativeformats));
1896                                                 if (res)
1897                                                         ast_log(LOG_WARNING, "Unable to set write format to %d\n", ast_best_codec(chan->nativeformats));
1898                                         }
1899                                         /* Check once more just in case */
1900                                         if (p->chan)
1901                                                 res = -1;
1902                                         if (callbackmode && !res) {
1903                                                 /* Just say goodbye and be done with it */
1904                                                 if (!ast_strlen_zero(p->loginchan)) {
1905                                                         if (p->loginstart == 0)
1906                                                                 time(&p->loginstart);
1907                                                         manager_event(EVENT_FLAG_AGENT, "Agentcallbacklogin",
1908                                                                       "Agent: %s\r\n"
1909                                                                       "Loginchan: %s\r\n"
1910                                                                       "Uniqueid: %s\r\n",
1911                                                                       p->agent, p->loginchan, chan->uniqueid);
1912                                                         ast_queue_log("NONE", chan->uniqueid, agent, "AGENTCALLBACKLOGIN", "%s", p->loginchan);
1913                                                         if (option_verbose > 1)
1914                                                                 ast_verbose(VERBOSE_PREFIX_2 "Callback Agent '%s' logged in on %s\n", p->agent, p->loginchan);
1915                                                         ast_device_state_changed("Agent/%s", p->agent);
1916                                                 } else {
1917                                                         logintime = time(NULL) - p->loginstart;
1918                                                         p->loginstart = 0;
1919                                                         manager_event(EVENT_FLAG_AGENT, "Agentcallbacklogoff",
1920                                                                       "Agent: %s\r\n"
1921                                                                       "Loginchan: %s\r\n"
1922                                                                       "Logintime: %ld\r\n"
1923                                                                       "Uniqueid: %s\r\n",
1924                                                                       p->agent, last_loginchan, logintime, chan->uniqueid);
1925                                                         ast_queue_log("NONE", chan->uniqueid, agent, "AGENTCALLBACKLOGOFF", "%s|%ld|", last_loginchan, logintime);
1926                                                         if (option_verbose > 1)
1927                                                                 ast_verbose(VERBOSE_PREFIX_2 "Callback Agent '%s' logged out\n", p->agent);
1928                                                         ast_device_state_changed("Agent/%s", p->agent);
1929                                                 }
1930                                                 ast_mutex_unlock(&agentlock);
1931                                                 if (!res)
1932                                                         res = ast_safe_sleep(chan, 500);
1933                                                 ast_mutex_unlock(&p->lock);
1934                                                 if (persistent_agents)
1935                                                         dump_agents();
1936                                         } else if (!res) {
1937 #ifdef HONOR_MUSIC_CLASS
1938                                                 /* check if the moh class was changed with setmusiconhold */
1939                                                 if (*(chan->musicclass))
1940                                                         ast_copy_string(p->moh, chan->musicclass, sizeof(p->moh));
1941 #endif                                                          
1942                                                 ast_moh_start(chan, p->moh);
1943                                                 if (p->loginstart == 0)
1944                                                         time(&p->loginstart);
1945                                                 manager_event(EVENT_FLAG_AGENT, "Agentlogin",
1946                                                               "Agent: %s\r\n"
1947                                                               "Channel: %s\r\n"
1948                                                               "Uniqueid: %s\r\n",
1949                                                               p->agent, chan->name, chan->uniqueid);
1950                                                 if (update_cdr && chan->cdr)
1951                                                         snprintf(chan->cdr->channel, sizeof(chan->cdr->channel), "Agent/%s", p->agent);
1952                                                 ast_queue_log("NONE", chan->uniqueid, agent, "AGENTLOGIN", "%s", chan->name);
1953                                                 if (option_verbose > 1)
1954                                                         ast_verbose(VERBOSE_PREFIX_2 "Agent '%s' logged in (format %s/%s)\n", p->agent,
1955                                                                     ast_getformatname(chan->readformat), ast_getformatname(chan->writeformat));
1956                                                 /* Login this channel and wait for it to
1957                                                    go away */
1958                                                 p->chan = chan;
1959                                                 if (p->ackcall > 1)
1960                                                         check_beep(p, 0);
1961                                                 else
1962                                                         check_availability(p, 0);
1963                                                 ast_mutex_unlock(&p->lock);
1964                                                 ast_mutex_unlock(&agentlock);
1965                                                 ast_device_state_changed("Agent/%s", p->agent);
1966                                                 while (res >= 0) {
1967                                                         ast_mutex_lock(&p->lock);
1968                                                         if (p->chan != chan)
1969                                                                 res = -1;
1970                                                         ast_mutex_unlock(&p->lock);
1971                                                         /* Yield here so other interested threads can kick in. */
1972                                                         sched_yield();
1973                                                         if (res)
1974                                                                 break;
1975
1976                                                         ast_mutex_lock(&agentlock);
1977                                                         ast_mutex_lock(&p->lock);
1978                                                         if (p->lastdisc.tv_sec) {
1979                                                                 if (ast_tvdiff_ms(ast_tvnow(), p->lastdisc) > p->wrapuptime) {
1980                                                                         if (option_debug)
1981                                                                                 ast_log(LOG_DEBUG, "Wrapup time for %s expired!\n", p->agent);
1982                                                                         p->lastdisc = ast_tv(0, 0);
1983                                                                         if (p->ackcall > 1)
1984                                                                                 check_beep(p, 0);
1985                                                                         else
1986                                                                                 check_availability(p, 0);
1987                                                                 }
1988                                                         }
1989                                                         ast_mutex_unlock(&p->lock);
1990                                                         ast_mutex_unlock(&agentlock);
1991                                                         /*      Synchronize channel ownership between call to agent and itself. */
1992                                                         ast_mutex_lock( &p->app_lock );
1993                                                         ast_mutex_lock(&p->lock);
1994                                                         p->owning_app = pthread_self();
1995                                                         ast_mutex_unlock(&p->lock);
1996                                                         if (p->ackcall > 1) 
1997                                                                 res = agent_ack_sleep(p);
1998                                                         else
1999                                                                 res = ast_safe_sleep_conditional( chan, 1000,
2000                                                                                                   agent_cont_sleep, p );
2001                                                         ast_mutex_unlock( &p->app_lock );
2002                                                         if ((p->ackcall > 1)  && (res == 1)) {
2003                                                                 ast_mutex_lock(&agentlock);
2004                                                                 ast_mutex_lock(&p->lock);
2005                                                                 check_availability(p, 0);
2006                                                                 ast_mutex_unlock(&p->lock);
2007                                                                 ast_mutex_unlock(&agentlock);
2008                                                                 res = 0;
2009                                                         }
2010                                                         sched_yield();
2011                                                 }
2012                                                 ast_mutex_lock(&p->lock);
2013                                                 if (res && p->owner) 
2014                                                         ast_log(LOG_WARNING, "Huh?  We broke out when there was still an owner?\n");
2015                                                 /* Log us off if appropriate */
2016                                                 if (p->chan == chan)
2017                                                         p->chan = NULL;
2018                                                 p->acknowledged = 0;
2019                                                 logintime = time(NULL) - p->loginstart;
2020                                                 p->loginstart = 0;
2021                                                 ast_mutex_unlock(&p->lock);
2022                                                 manager_event(EVENT_FLAG_AGENT, "Agentlogoff",
2023                                                               "Agent: %s\r\n"
2024                                                               "Logintime: %ld\r\n"
2025                                                               "Uniqueid: %s\r\n",
2026                                                               p->agent, logintime, chan->uniqueid);
2027                                                 ast_queue_log("NONE", chan->uniqueid, agent, "AGENTLOGOFF", "%s|%ld", chan->name, logintime);
2028                                                 if (option_verbose > 1)
2029                                                         ast_verbose(VERBOSE_PREFIX_2 "Agent '%s' logged out\n", p->agent);
2030                                                 /* If there is no owner, go ahead and kill it now */
2031                                                 ast_device_state_changed("Agent/%s", p->agent);
2032                                                 if (p->dead && !p->owner) {
2033                                                         ast_mutex_destroy(&p->lock);
2034                                                         ast_mutex_destroy(&p->app_lock);
2035                                                         free(p);
2036                                                 }
2037                                         }
2038                                         else {
2039                                                 ast_mutex_unlock(&p->lock);
2040                                                 p = NULL;
2041                                         }
2042                                         res = -1;
2043                                 } else {
2044                                         ast_mutex_unlock(&p->lock);
2045                                         errmsg = "agent-alreadyon";
2046                                         p = NULL;
2047                                 }
2048                                 break;
2049                         }
2050                         ast_mutex_unlock(&p->lock);
2051                         p = p->next;
2052                 }
2053                 if (!p)
2054                         ast_mutex_unlock(&agentlock);
2055
2056                 if (!res && (max_login_tries==0 || tries < max_login_tries))
2057                         res = ast_app_getdata(chan, errmsg, user, sizeof(user) - 1, 0);
2058         }
2059                 
2060         if (!res)
2061                 res = ast_safe_sleep(chan, 500);
2062
2063         /* AgentLogin() exit */
2064         if (!callbackmode) {
2065                 LOCAL_USER_REMOVE(u);
2066                 return -1;
2067         }
2068         /* AgentCallbackLogin() exit*/
2069         else {
2070                 /* Set variables */
2071                 if (login_state > 0) {
2072                         pbx_builtin_setvar_helper(chan, "AGENTNUMBER", user);
2073                         if (login_state==1) {
2074                                 pbx_builtin_setvar_helper(chan, "AGENTSTATUS", "on");
2075                                 pbx_builtin_setvar_helper(chan, "AGENTEXTEN", args.extension);
2076                         }
2077                         else {
2078                                 pbx_builtin_setvar_helper(chan, "AGENTSTATUS", "off");
2079                         }
2080                 }
2081                 else {
2082                         pbx_builtin_setvar_helper(chan, "AGENTSTATUS", "fail");
2083                 }
2084                 if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 1, chan->cid.cid_num)) {
2085                         LOCAL_USER_REMOVE(u);
2086                         return 0;
2087                 }
2088                 /* Do we need to play agent-goodbye now that we will be hanging up? */
2089                 if (play_announcement) {
2090                         if (!res)
2091                                 res = ast_safe_sleep(chan, 1000);
2092                         res = ast_streamfile(chan, agent_goodbye, chan->language);
2093                         if (!res)
2094                                 res = ast_waitstream(chan, "");
2095                         if (!res)
2096                                 res = ast_safe_sleep(chan, 1000);
2097                 }
2098         }
2099
2100         LOCAL_USER_REMOVE(u);
2101         
2102         /* We should never get here if next priority exists when in callbackmode */
2103         return -1;
2104 }
2105
2106 /**
2107  * Called by the AgentLogin application (from the dial plan).
2108  * 
2109  * @param chan
2110  * @param data
2111  * @returns
2112  * @sa callback_login_exec(), agentmonitoroutgoing_exec(), load_module().
2113  */
2114 static int login_exec(struct ast_channel *chan, void *data)
2115 {
2116         return __login_exec(chan, data, 0);
2117 }
2118
2119 /**
2120  *  Called by the AgentCallbackLogin application (from the dial plan).
2121  * 
2122  * @param chan
2123  * @param data
2124  * @returns
2125  * @sa login_exec(), agentmonitoroutgoing_exec(), load_module().
2126  */
2127 static int callback_exec(struct ast_channel *chan, void *data)
2128 {
2129         return __login_exec(chan, data, 1);
2130 }
2131
2132 /**
2133  * Sets an agent as logged in by callback in the Manager API.
2134  * It is registered on load_module() and it gets called by the manager backend.
2135  * @param s
2136  * @param m
2137  * @returns 
2138  * @sa action_agents(), action_agent_logoff(), load_module().
2139  */
2140 static int action_agent_callback_login(struct mansession *s, struct message *m)
2141 {
2142         char *agent = astman_get_header(m, "Agent");
2143         char *exten = astman_get_header(m, "Exten");
2144         char *context = astman_get_header(m, "Context");
2145         char *wrapuptime_s = astman_get_header(m, "WrapupTime");
2146         char *ackcall_s = astman_get_header(m, "AckCall");
2147         struct agent_pvt *p;
2148         int login_state = 0;
2149
2150         if (ast_strlen_zero(agent)) {
2151                 astman_send_error(s, m, "No agent specified");
2152                 return 0;
2153         }
2154
2155         if (ast_strlen_zero(exten)) {
2156                 astman_send_error(s, m, "No extension specified");
2157                 return 0;
2158         }
2159
2160         ast_mutex_lock(&agentlock);
2161         p = agents;
2162         while(p) {
2163                 if (strcmp(p->agent, agent) || p->pending) {
2164                         p = p->next;
2165                         continue;
2166                 }
2167                 if (p->chan) {
2168                         login_state = 2; /* already logged in (and on the phone)*/
2169                         break;
2170                 }
2171                 ast_mutex_lock(&p->lock);
2172                 login_state = 1; /* Successful Login */
2173                 
2174                 if (ast_strlen_zero(context))
2175                         ast_copy_string(p->loginchan, exten, sizeof(p->loginchan));
2176                 else
2177                         snprintf(p->loginchan, sizeof(p->loginchan), "%s@%s", exten, context);
2178
2179                 if (!ast_strlen_zero(wrapuptime_s)) {
2180                         p->wrapuptime = atoi(wrapuptime_s);
2181                         if (p->wrapuptime < 0)
2182                                 p->wrapuptime = 0;
2183                 }
2184
2185                 if (ast_true(ackcall_s))
2186                         p->ackcall = 1;
2187                 else
2188                         p->ackcall = 0;
2189
2190                 if (p->loginstart == 0)
2191                         time(&p->loginstart);
2192                 manager_event(EVENT_FLAG_AGENT, "Agentcallbacklogin",
2193                               "Agent: %s\r\n"
2194                               "Loginchan: %s\r\n",
2195                               p->agent, p->loginchan);
2196                 ast_queue_log("NONE", "NONE", agent, "AGENTCALLBACKLOGIN", "%s", p->loginchan);
2197                 if (option_verbose > 1)
2198                         ast_verbose(VERBOSE_PREFIX_2 "Callback Agent '%s' logged in on %s\n", p->agent, p->loginchan);
2199                 ast_device_state_changed("Agent/%s", p->agent);
2200                 ast_mutex_unlock(&p->lock);
2201                 p = p->next;
2202         }
2203         ast_mutex_unlock(&agentlock);
2204
2205         if (login_state == 1)
2206                 astman_send_ack(s, m, "Agent logged in");
2207         else if (login_state == 0)
2208                 astman_send_error(s, m, "No such agent");
2209         else if (login_state == 2)
2210                 astman_send_error(s, m, "Agent already logged in");
2211
2212         return 0;
2213 }
2214
2215 /**
2216  *  Called by the AgentMonitorOutgoing application (from the dial plan).
2217  *
2218  * @param chan
2219  * @param data
2220  * @returns
2221  * @sa login_exec(), callback_login_exec(), load_module().
2222  */
2223 static int agentmonitoroutgoing_exec(struct ast_channel *chan, void *data)
2224 {
2225         int exitifnoagentid = 0;
2226         int nowarnings = 0;
2227         int changeoutgoing = 0;
2228         int res = 0;
2229         char agent[AST_MAX_AGENT];
2230
2231         if (data) {
2232                 if (strchr(data, 'd'))
2233                         exitifnoagentid = 1;
2234                 if (strchr(data, 'n'))
2235                         nowarnings = 1;
2236                 if (strchr(data, 'c'))
2237                         changeoutgoing = 1;
2238         }
2239         if (chan->cid.cid_num) {
2240                 const char *tmp;
2241                 char agentvar[AST_MAX_BUF];
2242                 snprintf(agentvar, sizeof(agentvar), "%s_%s", GETAGENTBYCALLERID, chan->cid.cid_num);
2243                 if ((tmp = pbx_builtin_getvar_helper(NULL, agentvar))) {
2244                         struct agent_pvt *p = agents;
2245                         ast_copy_string(agent, tmp, sizeof(agent));
2246                         ast_mutex_lock(&agentlock);
2247                         while (p) {
2248                                 if (!strcasecmp(p->agent, tmp)) {
2249                                         if (changeoutgoing) snprintf(chan->cdr->channel, sizeof(chan->cdr->channel), "Agent/%s", p->agent);
2250                                         __agent_start_monitoring(chan, p, 1);
2251                                         break;
2252                                 }
2253                                 p = p->next;
2254                         }
2255                         ast_mutex_unlock(&agentlock);
2256                         
2257                 } else {
2258                         res = -1;
2259                         if (!nowarnings)
2260                                 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);
2261                 }
2262         } else {
2263                 res = -1;
2264                 if (!nowarnings)
2265                         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");
2266         }
2267         /* check if there is n + 101 priority */
2268         if (res) {
2269                 if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 101, chan->cid.cid_num)) {
2270                         chan->priority+=100;
2271                         if (option_verbose > 2)
2272                                 ast_verbose(VERBOSE_PREFIX_3 "Going to %d priority because there is no callerid or the agentid cannot be found.\n",chan->priority);
2273                 }
2274                 else if (exitifnoagentid)
2275                         return res;
2276         }
2277         return 0;
2278 }
2279
2280 /**
2281  * Dump AgentCallbackLogin agents to the database for persistence
2282  */
2283 static void dump_agents(void)
2284 {
2285         struct agent_pvt *cur_agent = NULL;
2286         char buf[256];
2287
2288         for (cur_agent = agents; cur_agent; cur_agent = cur_agent->next) {
2289                 if (cur_agent->chan)
2290                         continue;
2291
2292                 if (!ast_strlen_zero(cur_agent->loginchan)) {
2293                         snprintf(buf, sizeof(buf), "%s;%s", cur_agent->loginchan, cur_agent->logincallerid);
2294                         if (ast_db_put(pa_family, cur_agent->agent, buf))
2295                                 ast_log(LOG_WARNING, "failed to create persistent entry!\n");
2296                         else if (option_debug)
2297                                 ast_log(LOG_DEBUG, "Saved Agent: %s on %s\n", cur_agent->agent, cur_agent->loginchan);
2298                 } else {
2299                         /* Delete -  no agent or there is an error */
2300                         ast_db_del(pa_family, cur_agent->agent);
2301                 }
2302         }
2303 }
2304
2305 /**
2306  * Reload the persistent agents from astdb.
2307  */
2308 static void reload_agents(void)
2309 {
2310         char *agent_num;
2311         struct ast_db_entry *db_tree;
2312         struct ast_db_entry *entry;
2313         struct agent_pvt *cur_agent;
2314         char agent_data[256];
2315         char *parse;
2316         char *agent_chan;
2317         char *agent_callerid;
2318
2319         db_tree = ast_db_gettree(pa_family, NULL);
2320
2321         ast_mutex_lock(&agentlock);
2322         for (entry = db_tree; entry; entry = entry->next) {
2323                 agent_num = entry->key + strlen(pa_family) + 2;
2324                 cur_agent = agents;
2325                 while (cur_agent) {
2326                         ast_mutex_lock(&cur_agent->lock);
2327                         if (strcmp(agent_num, cur_agent->agent) == 0)
2328                                 break;
2329                         ast_mutex_unlock(&cur_agent->lock);
2330                         cur_agent = cur_agent->next;
2331                 }
2332                 if (!cur_agent) {
2333                         ast_db_del(pa_family, agent_num);
2334                         continue;
2335                 } else
2336                         ast_mutex_unlock(&cur_agent->lock);
2337                 if (!ast_db_get(pa_family, agent_num, agent_data, sizeof(agent_data)-1)) {
2338                         if (option_debug)
2339                                 ast_log(LOG_DEBUG, "Reload Agent: %s on %s\n", cur_agent->agent, agent_data);
2340                         parse = agent_data;
2341                         agent_chan = strsep(&parse, ";");
2342                         agent_callerid = strsep(&parse, ";");
2343                         ast_copy_string(cur_agent->loginchan, agent_chan, sizeof(cur_agent->loginchan));
2344                         if (agent_callerid) {
2345                                 ast_copy_string(cur_agent->logincallerid, agent_callerid, sizeof(cur_agent->logincallerid));
2346                                 set_agentbycallerid(cur_agent->logincallerid, cur_agent->agent);
2347                         } else
2348                                 cur_agent->logincallerid[0] = '\0';
2349                         if (cur_agent->loginstart == 0)
2350                                 time(&cur_agent->loginstart);
2351                         ast_device_state_changed("Agent/%s", cur_agent->agent); 
2352                 }
2353         }
2354         ast_mutex_unlock(&agentlock);
2355         if (db_tree) {
2356                 ast_log(LOG_NOTICE, "Agents sucessfully reloaded from database.\n");
2357                 ast_db_freetree(db_tree);
2358         }
2359 }
2360
2361 /*--- agent_devicestate: Part of PBX channel interface ---*/
2362 static int agent_devicestate(void *data)
2363 {
2364         struct agent_pvt *p;
2365         char *s;
2366         ast_group_t groupmatch;
2367         int groupoff;
2368         int waitforagent=0;
2369         int res = AST_DEVICE_INVALID;
2370         
2371         s = data;
2372         if ((s[0] == '@') && (sscanf(s + 1, "%d", &groupoff) == 1)) {
2373                 groupmatch = (1 << groupoff);
2374         } else if ((s[0] == ':') && (sscanf(s + 1, "%d", &groupoff) == 1)) {
2375                 groupmatch = (1 << groupoff);
2376                 waitforagent = 1;
2377         } else {
2378                 groupmatch = 0;
2379         }
2380
2381         /* Check actual logged in agents first */
2382         ast_mutex_lock(&agentlock);
2383         p = agents;
2384         while(p) {
2385                 ast_mutex_lock(&p->lock);
2386                 if (!p->pending && ((groupmatch && (p->group & groupmatch)) || !strcmp(data, p->agent))) {
2387                         if (p->owner) {
2388                                 if (res != AST_DEVICE_INUSE)
2389                                         res = AST_DEVICE_BUSY;
2390                         } else {
2391                                 if (res == AST_DEVICE_BUSY)
2392                                         res = AST_DEVICE_INUSE;
2393                                 if (p->chan || !ast_strlen_zero(p->loginchan)) {
2394                                         if (res == AST_DEVICE_INVALID)
2395                                                 res = AST_DEVICE_UNKNOWN;
2396                                 } else if (res == AST_DEVICE_INVALID)   
2397                                         res = AST_DEVICE_UNAVAILABLE;
2398                         }
2399                         if (!strcmp(data, p->agent)) {
2400                                 ast_mutex_unlock(&p->lock);
2401                                 break;
2402                         }
2403                 }
2404                 ast_mutex_unlock(&p->lock);
2405                 p = p->next;
2406         }
2407         ast_mutex_unlock(&agentlock);
2408         return res;
2409 }
2410
2411 struct agent_pvt *find_agent(char *agentid)
2412 {
2413         struct agent_pvt *cur = agents;
2414
2415         for (; cur; cur = cur->next) {
2416                 if (!strcmp(cur->agent, agentid))
2417                         break;  
2418         }
2419
2420         return cur;     
2421 }
2422
2423 static char *function_agent(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
2424 {
2425         char *agentid;
2426         char *item;
2427         char *tmp;
2428         struct agent_pvt *agent;
2429
2430         buf[0] = '\0';
2431
2432         if (ast_strlen_zero(data)) {
2433                 ast_log(LOG_WARNING, "The AGENT function requires an argument - agentid!\n");
2434                 return buf;     
2435         }
2436
2437         item = ast_strdupa(data);
2438         if (!item) {
2439                 ast_log(LOG_ERROR, "Out of memory!\n");
2440                 return buf;
2441         }
2442
2443         agentid = strsep(&item, ":");
2444         if (!item)
2445                 item = "status";
2446
2447         agent = find_agent(agentid);
2448         if (!agent) {
2449                 ast_log(LOG_WARNING, "Agent '%s' not found!\n", agentid);
2450                 return buf;
2451         }
2452
2453         if (!strcasecmp(item, "status")) {
2454                 if (agent->chan || !ast_strlen_zero(agent->loginchan)) {
2455                         ast_copy_string(buf, "LOGGEDIN", len);
2456                 } else {
2457                         ast_copy_string(buf, "LOGGEDOUT", len);
2458                 }
2459         } else if (!strcasecmp(item, "password")) {
2460                 ast_copy_string(buf, agent->password, len);
2461         } else if (!strcasecmp(item, "name")) {
2462                 ast_copy_string(buf, agent->name, len);
2463         } else if (!strcasecmp(item, "mohclass")) {
2464                 ast_copy_string(buf, agent->moh, len);
2465         } else if (!strcasecmp(item, "channel")) {
2466                 if (agent->chan) {
2467                         ast_copy_string(buf, agent->chan->name, len);
2468                         tmp = strrchr(buf, '-');
2469                         if (tmp)
2470                                 *tmp = '\0';
2471                 } 
2472         } else if (!strcasecmp(item, "exten")) {
2473                 ast_copy_string(buf, agent->loginchan, len);    
2474         }
2475
2476         return buf;
2477 }
2478
2479 struct ast_custom_function agent_function = {
2480         .name = "AGENT",
2481         .synopsis = "Gets information about an Agent",
2482         .syntax = "AGENT(<agentid>[:item])",
2483         .read = function_agent,
2484         .desc = "The valid items to retrieve are:\n"
2485         "- status (default)      The status of the agent\n"
2486         "                          LOGGEDIN | LOGGEDOUT\n"
2487         "- password              The password of the agent\n"
2488         "- name                  The name of the agent\n"
2489         "- mohclass              MusicOnHold class\n"
2490         "- exten                 The callback extension for the Agent (AgentCallbackLogin)\n"
2491         "- channel               The name of the active channel for the Agent (AgentLogin)\n"
2492 };
2493
2494
2495 /**
2496  * Initialize the Agents module.
2497  * This funcion is being called by Asterisk when loading the module. Among other thing it registers applications, cli commands and reads the cofiguration file.
2498  *
2499  * @returns int Always 0.
2500  */
2501 int load_module()
2502 {
2503         /* Make sure we can register our agent channel type */
2504         if (ast_channel_register(&agent_tech)) {
2505                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", channeltype);
2506                 return -1;
2507         }
2508         /* Dialplan applications */
2509         ast_register_application(app, login_exec, synopsis, descrip);
2510         ast_register_application(app2, callback_exec, synopsis2, descrip2);
2511         ast_register_application(app3, agentmonitoroutgoing_exec, synopsis3, descrip3);
2512         /* Manager commands */
2513         ast_manager_register2("Agents", EVENT_FLAG_AGENT, action_agents, "Lists agents and their status", mandescr_agents);
2514         ast_manager_register2("AgentLogoff", EVENT_FLAG_AGENT, action_agent_logoff, "Sets an agent as no longer logged in", mandescr_agent_logoff);
2515         ast_manager_register2("AgentCallbackLogin", EVENT_FLAG_AGENT, action_agent_callback_login, "Sets an agent as logged in by callback", mandescr_agent_callback_login);
2516         /* CLI Commands */
2517         ast_cli_register(&cli_show_agents);
2518         ast_cli_register(&cli_agent_logoff);
2519         /* Dialplan Functions */
2520         ast_custom_function_register(&agent_function);
2521         /* Read in the config */
2522         read_agent_config();
2523         if (persistent_agents)
2524                 reload_agents();
2525         return 0;
2526 }
2527
2528 int reload()
2529 {
2530         read_agent_config();
2531         if (persistent_agents)
2532                 reload_agents();
2533         return 0;
2534 }
2535
2536 int unload_module()
2537 {
2538         struct agent_pvt *p;
2539         /* First, take us out of the channel loop */
2540         /* Unregister dialplan functions */
2541         ast_custom_function_unregister(&agent_function);        
2542         /* Unregister CLI commands */
2543         ast_cli_unregister(&cli_show_agents);
2544         ast_cli_unregister(&cli_agent_logoff);
2545         /* Unregister dialplan applications */
2546         ast_unregister_application(app);
2547         ast_unregister_application(app2);
2548         ast_unregister_application(app3);
2549         /* Unregister manager command */
2550         ast_manager_unregister("Agents");
2551         ast_manager_unregister("AgentLogoff");
2552         ast_manager_unregister("AgentCallbackLogin");
2553         /* Unregister channel */
2554         ast_channel_unregister(&agent_tech);
2555         if (!ast_mutex_lock(&agentlock)) {
2556                 /* Hangup all interfaces if they have an owner */
2557                 p = agents;
2558                 while(p) {
2559                         if (p->owner)
2560                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
2561                         p = p->next;
2562                 }
2563                 agents = NULL;
2564                 ast_mutex_unlock(&agentlock);
2565         } else {
2566                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
2567                 return -1;
2568         }               
2569         return 0;
2570 }
2571
2572 int usecount()
2573 {
2574         return usecnt;
2575 }
2576
2577 char *key()
2578 {
2579         return ASTERISK_GPL_KEY;
2580 }
2581
2582 char *description()
2583 {
2584         return (char *) desc;
2585 }
2586