Create concept of a "pending agent", so you can have agents access pending calls
[asterisk/asterisk.git] / channels / chan_agent.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Implementation of Session Initiation Protocol
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdio.h>
15 #include <pthread.h>
16 #include <string.h>
17 #include <asterisk/lock.h>
18 #include <asterisk/channel.h>
19 #include <asterisk/channel_pvt.h>
20 #include <asterisk/config.h>
21 #include <asterisk/logger.h>
22 #include <asterisk/module.h>
23 #include <asterisk/pbx.h>
24 #include <asterisk/options.h>
25 #include <asterisk/lock.h>
26 #include <asterisk/sched.h>
27 #include <asterisk/io.h>
28 #include <asterisk/rtp.h>
29 #include <asterisk/acl.h>
30 #include <asterisk/callerid.h>
31 #include <asterisk/file.h>
32 #include <asterisk/cli.h>
33 #include <asterisk/app.h>
34 #include <asterisk/musiconhold.h>
35 #include <asterisk/manager.h>
36 #include <asterisk/parking.h>
37 #include <sys/socket.h>
38 #include <errno.h>
39 #include <unistd.h>
40 #include <stdlib.h>
41 #include <fcntl.h>
42 #include <netdb.h>
43 #include <arpa/inet.h>
44 #include <sys/signal.h>
45
46 static char *desc = "Agent Proxy Channel";
47 static char *type = "Agent";
48 static char *tdesc = "Call Agent Proxy Channel";
49 static char *config = "agents.conf";
50
51 static char *app = "AgentLogin";
52
53 static char *synopsis = "Call agent login";
54
55 static char *descrip =
56 "  AgentLogin([AgentNo][|options]):\n"
57 "Asks the agent to login to the system.  Always returns -1.  While\n"
58 "logged in, the agent can receive calls and will hear a 'beep'\n"
59 "when a new call comes in.  The agent can dump the call by pressing\n"
60 "the star key.\n"
61 "The option string may contain zero or more of the following characters:\n"
62 "      's' -- silent login - do not announce the login ok segment\n";
63
64 static char moh[80] = "default";
65
66 #define AST_MAX_AGENT   80              /* Agent ID or Password max length */
67
68 static int capability = -1;
69
70 static unsigned int group;
71
72 static int usecnt =0;
73 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
74
75 /* Protect the interface list (of sip_pvt's) */
76 static pthread_mutex_t agentlock = AST_MUTEX_INITIALIZER;
77
78 static struct agent_pvt {
79         pthread_mutex_t lock;                           /* Channel private lock */
80         int dead;                                                       /* Poised for destruction? */
81         int pending;                                            /* Not a real agent -- just pending a match */
82         unsigned int group;                                     /* Group memberships */
83         char moh[80];                                           /* Which music on hold */
84         char agent[AST_MAX_AGENT];                      /* Agent ID */
85         char password[AST_MAX_AGENT];           /* Password for Agent login */
86         char name[AST_MAX_AGENT];
87         pthread_mutex_t app_lock;                       /* Synchronization between owning applications */
88         volatile pthread_t owning_app;          /* Owning application thread id */
89         volatile int app_sleep_cond;            /* Sleep condition for the login app */
90         struct ast_channel *owner;                      /* Agent */
91         struct ast_channel *chan;                       /* Channel we use */
92         struct agent_pvt *next;                         /* Agent */
93 } *agents = NULL;
94
95 #define CLEANUP(ast, p) do { \
96         int x; \
97         if (p->chan) { \
98                 for (x=0;x<AST_MAX_FDS;x++) \
99                         ast->fds[x] = p->chan->fds[x]; \
100         } \
101 } while(0)
102
103
104 static void agent_unlink(struct agent_pvt *agent)
105 {
106         struct agent_pvt *p, *prev;
107         prev = NULL;
108         p = agents;
109         while(p) {
110                 if (p == agent) {
111                         if (prev)
112                                 prev->next = agent->next;
113                         else
114                                 agents = agent->next;
115                         break;
116                 }
117                 prev = p;
118                 p = p->next;
119         }
120 }
121
122 static struct agent_pvt *add_agent(char *agent, int pending)
123 {
124         char tmp[256];
125         char *password=NULL, *name=NULL;
126         struct agent_pvt *p, *prev;
127         
128         strncpy(tmp, agent, sizeof(tmp));
129         if ((password = strchr(tmp, ','))) {
130                 *password = '\0';
131                 password++;
132                 while (*password < 33) password++;
133         }
134         if (password && (name = strchr(password, ','))) {
135                 *name = '\0';
136                 name++;
137                 while (*name < 33) name++; 
138         }
139         prev=NULL;
140         p = agents;
141         while(p) {
142                 if (!pending && !strcmp(p->agent, tmp))
143                         break;
144                 prev = p;
145                 p = p->next;
146         }
147         if (!p) {
148                 p = malloc(sizeof(struct agent_pvt));
149                 if (p) {
150                         memset(p, 0, sizeof(struct agent_pvt));
151                         strncpy(p->agent, tmp, sizeof(p->agent) -1);
152                         ast_pthread_mutex_init( &p->lock );
153                         ast_pthread_mutex_init( &p->app_lock );
154                         p->owning_app = -1;
155                         p->app_sleep_cond = 1;
156                         p->group = group;
157                         p->pending = pending;
158                         p->next = NULL;
159                         if (prev)
160                                 prev->next = p;
161                         else
162                                 agents = p;
163                         
164                 }
165         }
166         if (!p)
167                 return NULL;
168         strncpy(p->password, password ? password : "", sizeof(p->password) - 1);
169         strncpy(p->name, name ? name : "", sizeof(p->name) - 1);
170         strncpy(p->moh, moh, sizeof(p->moh) - 1);
171         if (pending)
172                 p->dead = 1;
173         else
174                 p->dead = 0;
175         return p;
176 }
177
178 static int check_availability(struct agent_pvt *newlyavailable, int needlock);
179
180 static int agent_answer(struct ast_channel *ast)
181 {
182         ast_log(LOG_WARNING, "Huh?  Agent is being asked to answer?\n");
183         return -1;
184 }
185
186 static struct ast_frame  *agent_read(struct ast_channel *ast)
187 {
188         struct agent_pvt *p = ast->pvt->pvt;
189         struct ast_frame *f = NULL;
190         static struct ast_frame null_frame = { AST_FRAME_NULL, };
191         ast_pthread_mutex_lock(&p->lock);
192         if (p->chan)
193                 f = ast_read(p->chan);
194         else
195                 f = &null_frame;
196         if (!f) {
197                 /* If there's a channel, make it NULL */
198                 if (p->chan)
199                         p->chan = NULL;
200         }
201         if (f && (f->frametype == AST_FRAME_DTMF) && (f->subclass == '*')) {
202                 /* * terminates call */
203                 ast_frfree(f);
204                 f = NULL;
205         }
206         CLEANUP(ast,p);
207         ast_pthread_mutex_unlock(&p->lock);
208         return f;
209 }
210
211 static int agent_write(struct ast_channel *ast, struct ast_frame *f)
212 {
213         struct agent_pvt *p = ast->pvt->pvt;
214         int res = -1;
215         ast_pthread_mutex_lock(&p->lock);
216         if (p->chan)
217                 res = ast_write(p->chan, f);
218         else
219                 res = 0;
220         CLEANUP(ast, p);
221         ast_pthread_mutex_unlock(&p->lock);
222         return res;
223 }
224
225 static int agent_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
226 {
227         struct agent_pvt *p = newchan->pvt->pvt;
228         ast_pthread_mutex_lock(&p->lock);
229         if (p->owner != oldchan) {
230                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
231                 ast_pthread_mutex_unlock(&p->lock);
232                 return -1;
233         }
234         p->owner = newchan;
235         ast_pthread_mutex_unlock(&p->lock);
236         return 0;
237 }
238
239 static int agent_indicate(struct ast_channel *ast, int condition)
240 {
241         struct agent_pvt *p = ast->pvt->pvt;
242         int res = -1;
243         ast_pthread_mutex_lock(&p->lock);
244         if (p->chan)
245                 res = ast_indicate(p->chan, condition);
246         else
247                 res = 0;
248         ast_pthread_mutex_unlock(&p->lock);
249         return res;
250 }
251
252 static int agent_digit(struct ast_channel *ast, char digit)
253 {
254         struct agent_pvt *p = ast->pvt->pvt;
255         int res = -1;
256         ast_pthread_mutex_lock(&p->lock);
257         if (p->chan)
258                 res = p->chan->pvt->send_digit(p->chan, digit);
259         else
260                 res = 0;
261         ast_pthread_mutex_unlock(&p->lock);
262         return res;
263 }
264
265 static int agent_call(struct ast_channel *ast, char *dest, int timeout)
266 {
267         struct agent_pvt *p = ast->pvt->pvt;
268         int res = -1;
269         ast_pthread_mutex_lock(&p->lock);
270         if (!p->chan) {
271                 if (p->pending) {
272                         ast_log(LOG_DEBUG, "Pretending to dial on pending agent\n");
273                         ast_setstate(ast, AST_STATE_DIALING);
274                         res = 0;
275                 } else {
276                         ast_log(LOG_NOTICE, "Whoa, they hung up between alloc and call...  what are the odds of that?\n");
277                         res = -1;
278                 }
279                 ast_pthread_mutex_unlock(&p->lock);
280                 return res;
281         }
282         ast_verbose( VERBOSE_PREFIX_3 "agent_call, call to agent '%s' call on '%s'\n", p->agent, p->chan->name);
283         ast_log( LOG_DEBUG, "Playing beep, lang '%s'\n", p->chan->language);
284         res = ast_streamfile(p->chan, "beep", p->chan->language);
285         ast_log( LOG_DEBUG, "Played beep, result '%d'\n", res);
286         if (!res) {
287                 res = ast_waitstream(p->chan, "");
288                 ast_log( LOG_DEBUG, "Waited for stream, result '%d'\n", res);
289         }
290         if (!res) {
291                 res = ast_set_read_format(p->chan, ast_best_codec(p->chan->nativeformats));
292                 ast_log( LOG_DEBUG, "Set read format, result '%d'\n", res);
293                 if (res)
294                         ast_log(LOG_WARNING, "Unable to set read format to %d\n", ast_best_codec(p->chan->nativeformats));
295         } else {
296                 // Agent hung-up
297                 p->chan = NULL;
298         }
299
300         if (!res) {
301                 ast_set_write_format(p->chan, ast_best_codec(p->chan->nativeformats));
302                 ast_log( LOG_DEBUG, "Set write format, result '%d'\n", res);
303                 if (res)
304                         ast_log(LOG_WARNING, "Unable to set write format to %d\n", ast_best_codec(p->chan->nativeformats));
305         }
306         if( !res )
307         {
308                 /* Call is immediately up */
309                 ast_setstate(ast, AST_STATE_UP);
310         }
311         CLEANUP(ast,p);
312         ast_pthread_mutex_unlock(&p->lock);
313         return res;
314 }
315
316 static int agent_hangup(struct ast_channel *ast)
317 {
318         struct agent_pvt *p = ast->pvt->pvt;
319         ast_pthread_mutex_lock(&p->lock);
320         p->owner = NULL;
321         ast->pvt->pvt = NULL;
322         p->app_sleep_cond = 1;
323         if (p->chan) {
324                 /* If they're dead, go ahead and hang up on the agent now */
325                 ast_pthread_mutex_lock(&p->chan->lock);
326                 if (p->dead)
327                         ast_softhangup(p->chan, AST_SOFTHANGUP_EXPLICIT);
328                 ast_moh_start(p->chan, p->moh);
329                 ast_pthread_mutex_unlock(&p->chan->lock);
330         }
331 #if 0
332                 ast_pthread_mutex_unlock(&p->lock);
333                 /* Release ownership of the agent to other threads (presumably running the login app). */
334                 ast_pthread_mutex_unlock(&p->app_lock);
335         } else if (p->dead) {
336                 /* Go ahead and lose it */
337                 ast_pthread_mutex_unlock(&p->lock);
338                 /* Release ownership of the agent to other threads (presumably running the login app). */
339                 ast_pthread_mutex_unlock(&p->app_lock);
340         } else {
341                 ast_pthread_mutex_unlock(&p->lock);
342                 /* Release ownership of the agent to other threads (presumably running the login app). */
343                 ast_pthread_mutex_unlock(&p->app_lock);
344         }
345 #endif  
346         ast_pthread_mutex_unlock(&p->lock);
347         /* Release ownership of the agent to other threads (presumably running the login app). */
348         ast_pthread_mutex_unlock(&p->app_lock);
349
350         if (p->pending) {
351                 agent_unlink(p);
352         }
353         if (p->dead)
354                 free(p);
355         else {
356                 /* Not dead -- check availability now */
357                 ast_pthread_mutex_lock(&p->lock);
358                 check_availability(p, 1);
359                 ast_pthread_mutex_unlock(&p->lock);
360         }
361         return 0;
362 }
363
364 static int agent_cont_sleep( void *data )
365 {
366         struct agent_pvt *p;
367         int res;
368
369         p = (struct agent_pvt *)data;
370
371         ast_pthread_mutex_lock(&p->lock);
372         res = p->app_sleep_cond;
373         ast_pthread_mutex_unlock(&p->lock);
374 #if 0
375         if( !res )
376                 ast_log( LOG_DEBUG, "agent_cont_sleep() returning %d\n", res );
377 #endif          
378         return res;
379 }
380
381 static struct ast_channel *agent_new(struct agent_pvt *p, int state)
382 {
383         struct ast_channel *tmp;
384         struct ast_frame null_frame = { AST_FRAME_NULL };
385 #if 0
386         if (!p->chan) {
387                 ast_log(LOG_WARNING, "No channel? :(\n");
388                 return NULL;
389         }
390 #endif  
391         tmp = ast_channel_alloc(0);
392         if (tmp) {
393                 if (p->chan) {
394                         tmp->nativeformats = p->chan->nativeformats;
395                         tmp->writeformat = p->chan->writeformat;
396                         tmp->pvt->rawwriteformat = p->chan->writeformat;
397                         tmp->readformat = p->chan->readformat;
398                         tmp->pvt->rawreadformat = p->chan->readformat;
399                         strncpy(tmp->language, p->chan->language, sizeof(tmp->language)-1);
400                         strncpy(tmp->context, p->chan->context, sizeof(tmp->context)-1);
401                         strncpy(tmp->exten, p->chan->exten, sizeof(tmp->exten)-1);
402                 } else {
403                         tmp->nativeformats = AST_FORMAT_SLINEAR;
404                         tmp->writeformat = AST_FORMAT_SLINEAR;
405                         tmp->pvt->rawwriteformat = AST_FORMAT_SLINEAR;
406                         tmp->readformat = AST_FORMAT_SLINEAR;
407                         tmp->pvt->rawreadformat = AST_FORMAT_SLINEAR;
408                 }
409                 if (p->pending)
410                         snprintf(tmp->name, sizeof(tmp->name), "Agent/P%s-%d", p->agent, rand() & 0xffff);
411                 else
412                         snprintf(tmp->name, sizeof(tmp->name), "Agent/%s", p->agent);
413                 tmp->type = type;
414                 ast_setstate(tmp, state);
415                 tmp->pvt->pvt = p;
416                 tmp->pvt->send_digit = agent_digit;
417                 tmp->pvt->call = agent_call;
418                 tmp->pvt->hangup = agent_hangup;
419                 tmp->pvt->answer = agent_answer;
420                 tmp->pvt->read = agent_read;
421                 tmp->pvt->write = agent_write;
422                 tmp->pvt->exception = agent_read;
423                 tmp->pvt->indicate = agent_indicate;
424                 tmp->pvt->fixup = agent_fixup;
425                 p->owner = tmp;
426                 ast_pthread_mutex_lock(&usecnt_lock);
427                 usecnt++;
428                 ast_pthread_mutex_unlock(&usecnt_lock);
429                 ast_update_use_count();
430                 tmp->priority = 1;
431                 /* Wake up and wait for other applications (by definition the login app)
432                  * to release this channel). Takes ownership of the agent channel
433                  * to this thread only.
434                  * For signalling the other thread, ast_queue_frame is used until we
435                  * can safely use signals for this purpose. The pselect() needs to be
436                  * implemented in the kernel for this.
437                  */
438                 p->app_sleep_cond = 0;
439                 if( pthread_mutex_trylock(&p->app_lock) )
440                 {
441                         ast_queue_frame(p->chan, &null_frame, 1);
442                         ast_pthread_mutex_unlock(&p->lock);     /* For other thread to read the condition. */
443                         ast_pthread_mutex_lock(&p->app_lock);
444                         ast_pthread_mutex_lock(&p->lock);
445                         if( !p->chan )
446                         {
447                                 ast_log(LOG_WARNING, "Agent disconnected while we were connecting the call\n");
448                                 p->owner = NULL;
449                                 tmp->pvt->pvt = NULL;
450                                 p->app_sleep_cond = 1;
451                                 ast_channel_free( tmp );
452                                 return NULL;
453                         }
454                 }
455                 p->owning_app = pthread_self();
456                 /* After the above step, there should not be any blockers. */
457                 if (p->chan) {
458                         if (p->chan->blocking) {
459                                 ast_log( LOG_ERROR, "A blocker exists after agent channel ownership acquired\n" );
460                                 CRASH;
461                         }
462                         ast_moh_stop(p->chan);
463                 }
464         } else
465                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
466         return tmp;
467 }
468
469
470 static int read_agent_config(void)
471 {
472         struct ast_config *cfg;
473         struct ast_variable *v;
474         struct agent_pvt *p, *pl, *pn;
475         group = 0;
476         cfg = ast_load(config);
477         if (!cfg) {
478                 ast_log(LOG_NOTICE, "No agent configuration found -- agent support disabled\n");
479                 return 0;
480         }
481         ast_pthread_mutex_lock(&agentlock);
482         p = agents;
483         while(p) {
484                 p->dead = 1;
485                 p = p->next;
486         }
487         strcpy(moh, "default");
488         v = ast_variable_browse(cfg, "agents");
489         while(v) {
490                 /* Create the interface list */
491                 if (!strcasecmp(v->name, "agent")) {
492                         add_agent(v->value, 0);
493                 } else if (!strcasecmp(v->name, "group")) {
494                         group = ast_get_group(v->value);
495                 } else if (!strcasecmp(v->name, "musiconhold")) {
496                         strncpy(moh, v->value, sizeof(moh) - 1);
497                 }
498                 v = v->next;
499         }
500         p = agents;
501         pl = NULL;
502         while(p) {
503                 pn = p->next;
504                 if (p->dead) {
505                         /* Unlink */
506                         if (pl)
507                                 pl->next = p->next;
508                         else
509                                 agents = p->next;
510                         /* Destroy if  appropriate */
511                         if (!p->owner) {
512                                 if (!p->chan) {
513                                         free(p);
514                                 } else {
515                                         /* Cause them to hang up */
516                                         ast_softhangup(p->chan, AST_SOFTHANGUP_EXPLICIT);
517                                 }
518                         }
519                 } else
520                         pl = p;
521                 p = pn;
522         }
523         ast_pthread_mutex_unlock(&agentlock);
524         ast_destroy(cfg);
525         return 0;
526 }
527
528 static int check_availability(struct agent_pvt *newlyavailable, int needlock)
529 {
530         struct ast_channel *chan=NULL, *parent=NULL;
531         struct agent_pvt *p;
532         int res;
533         ast_log(LOG_DEBUG, "Checking availability of '%s'\n", newlyavailable->agent);
534         if (needlock)
535                 ast_pthread_mutex_lock(&agentlock);
536         p = agents;
537         while(p) {
538                 if (p == newlyavailable) {
539                         p = p->next;
540                         continue;
541                 }
542                 ast_pthread_mutex_lock(&p->lock);
543                 if (p->pending && ((p->group && (newlyavailable->group & p->group)) || !strcmp(p->agent, newlyavailable->agent))) {
544                         ast_log(LOG_DEBUG, "Call '%s' looks like a winner for agent '%s'\n", p->owner->name, newlyavailable->agent);
545                         /* We found a pending call, time to merge */
546                         chan = agent_new(newlyavailable, AST_STATE_DOWN);
547                         parent = p->owner;
548                         ast_pthread_mutex_unlock(&p->lock);
549                         break;
550                 }
551                 ast_pthread_mutex_unlock(&p->lock);
552                 p = p->next;
553         }
554         if (needlock)
555                 ast_pthread_mutex_unlock(&agentlock);
556         if (parent && chan)  {
557                 ast_log( LOG_DEBUG, "Playing beep, lang '%s'\n", newlyavailable->chan->language);
558                 res = ast_streamfile(newlyavailable->chan, "beep", newlyavailable->chan->language);
559                 ast_log( LOG_DEBUG, "Played beep, result '%d'\n", res);
560                 if (!res) {
561                         res = ast_waitstream(newlyavailable->chan, "");
562                         ast_log( LOG_DEBUG, "Waited for stream, result '%d'\n", res);
563                 }
564                 if (!res) {
565                         ast_setstate(parent, AST_STATE_UP);
566                         ast_setstate(chan, AST_STATE_UP);
567                         ast_channel_masquerade(parent, chan);
568                         ast_hangup(chan);
569                 } else {
570                         ast_log(LOG_NOTICE, "Not sure this will always work..\n");
571                         ast_hangup(chan);
572                 }
573         }
574         return 0;
575 }
576
577 static struct ast_channel *agent_request(char *type, int format, void *data)
578 {
579         struct agent_pvt *p;
580         struct ast_channel *chan = NULL;
581         char *s;
582         unsigned int groupmatch;
583         int waitforagent=0;
584         s = data;
585         if ((s[0] == '@') && (sscanf(s + 1, "%d", &groupmatch) == 1)) {
586                 groupmatch = (1 << groupmatch);
587         } else if ((s[0] == ':') && (sscanf(s + 1, "%d", &groupmatch) == 1)) {
588                 groupmatch = (1 << groupmatch);
589                 waitforagent = 1;
590         } else {
591                 groupmatch = 0;
592         }
593         ast_pthread_mutex_lock(&agentlock);
594         p = agents;
595         while(p) {
596                 ast_pthread_mutex_lock(&p->lock);
597                 if (!p->pending && ((groupmatch && (p->group & groupmatch)) || !strcmp(data, p->agent))) {
598                         /* Agent must be registered, but not have any active call */
599                         if (!p->owner && p->chan) {
600                                 chan = agent_new(p, AST_STATE_DOWN);
601                         }
602                         ast_pthread_mutex_unlock(&p->lock);
603                         break;
604                 }
605                 ast_pthread_mutex_unlock(&p->lock);
606                 p = p->next;
607         }
608         if (!chan && waitforagent) {
609                 /* No agent available -- but we're requesting to wait for one.
610                    Allocate a place holder */
611                 ast_log(LOG_DEBUG, "Creating place holder for '%s'\n", s);
612                 p = add_agent(data, 1);
613                 p->group = groupmatch;
614                 chan = agent_new(p, AST_STATE_DOWN);
615                 if (!chan) {
616                         ast_log(LOG_WARNING, "Weird...  Fix this to drop the unused pending agent\n");
617                 }
618         }
619         ast_pthread_mutex_unlock(&agentlock);
620         return chan;
621 }
622
623 static int powerof(unsigned int v)
624 {
625         int x;
626         for (x=0;x<32;x++) {
627                 if (v & (1 << x)) return x;
628         }
629         return 0;
630 }
631
632 static int agents_show(int fd, int argc, char **argv)
633 {
634         struct agent_pvt *p;
635         char username[256];
636         char location[256];
637         char talkingto[256];
638
639         if (argc != 2)
640                 return RESULT_SHOWUSAGE;
641         ast_pthread_mutex_lock(&agentlock);
642         p = agents;
643         while(p) {
644                 ast_pthread_mutex_lock(&p->lock);
645                 if (p->pending) {
646                         if (p->group)
647                                 ast_cli(fd, "-- Pending call to group %d\n", powerof(p->group));
648                         else
649                                 ast_cli(fd, "-- Pending call to agent %s\n", p->agent);
650                 } else {
651                         if (strlen(p->name))
652                                 snprintf(username, sizeof(username), "(%s) ", p->name);
653                         else
654                                 strcpy(username, "");
655                         if (p->chan) {
656                                 snprintf(location, sizeof(location), "logged in on %s", p->chan->name);
657                                 if (p->owner && p->owner->bridge) {
658                                         snprintf(talkingto, sizeof(talkingto), " talking to %s", p->owner->bridge->name);
659                                 } else {
660                                         strcpy(talkingto, " is idle");
661                                 }
662                         } else {
663                                 strcpy(location, "not logged in");
664                                 strcpy(talkingto, "");
665                         }
666                         ast_cli(fd, "%-12.12s %s%s%s\n", p->agent, 
667                                         username, location, talkingto);
668                 }
669                 ast_pthread_mutex_unlock(&p->lock);
670                 p = p->next;
671         }
672         ast_pthread_mutex_unlock(&agentlock);
673         return RESULT_SUCCESS;
674 }
675
676 static char show_agents_usage[] = 
677 "Usage: show agents\n"
678 "       Provides summary information on agents.\n";
679
680 static struct ast_cli_entry cli_show_agents = {
681         { "show", "agents", NULL }, agents_show, 
682         "Show status of agents", show_agents_usage, NULL };
683
684 STANDARD_LOCAL_USER;
685 LOCAL_USER_DECL;
686
687 static int login_exec(struct ast_channel *chan, void *data)
688 {
689         int res=0;
690         int tries = 0;
691         struct agent_pvt *p;
692         struct localuser *u;
693         char user[AST_MAX_AGENT];
694         char pass[AST_MAX_AGENT];
695         char xpass[AST_MAX_AGENT] = "";
696         char *errmsg;
697         char info[512];
698         char *opt_user = NULL;
699         char *options = NULL;
700         int play_announcement;
701         
702         LOCAL_USER_ADD(u);
703
704         /* Parse the arguments XXX Check for failure XXX */
705         strncpy(info, (char *)data, strlen((char *)data) + AST_MAX_EXTENSION-1);
706         opt_user = info;
707         if( opt_user ) {
708                 options = strchr(opt_user, '|');
709                 if (options) {
710                         *options = '\0';
711                         options++;
712                 }
713         }
714
715         if (chan->_state != AST_STATE_UP)
716                 res = ast_answer(chan);
717         if (!res) {
718                 if( opt_user && strlen(opt_user))
719                         strncpy( user, opt_user, AST_MAX_AGENT );
720                 else
721                         res = ast_app_getdata(chan, "agent-user", user, sizeof(user) - 1, 0);
722         }
723         while (!res && (tries < 3)) {
724                 /* Check for password */
725                 ast_pthread_mutex_lock(&agentlock);
726                 p = agents;
727                 while(p) {
728                         if (!strcmp(p->agent, user) && !p->pending)
729                                 strncpy(xpass, p->password, sizeof(xpass) - 1);
730                         p = p->next;
731                 }
732                 ast_pthread_mutex_unlock(&agentlock);
733                 if (!res) {
734                         if (strlen(xpass))
735                                 res = ast_app_getdata(chan, "agent-pass", pass, sizeof(pass) - 1, 0);
736                         else
737                                 strcpy(pass, "");
738                 }
739                 errmsg = "agent-incorrect";
740
741 #if 0
742                 ast_log(LOG_NOTICE, "user: %s, pass: %s\n", user, pass);
743 #endif          
744
745                 /* Check again for accuracy */
746                 ast_pthread_mutex_lock(&agentlock);
747                 p = agents;
748                 while(p) {
749                         ast_pthread_mutex_lock(&p->lock);
750                         if (!strcmp(p->agent, user) &&
751                                 !strcmp(p->password, pass) && !p->pending) {
752                                         if (!p->chan) {
753                                                 play_announcement = 1;
754                                                 if( options )
755                                                         if( strchr( options, 's' ) )
756                                                                 play_announcement = 0;
757                                                 if( play_announcement )
758                                                         res = ast_streamfile(chan, "agent-loginok", chan->language);
759                                                 if (!res)
760                                                         ast_waitstream(chan, "");
761                                                 if (!res) {
762                                                         res = ast_set_read_format(chan, ast_best_codec(chan->nativeformats));
763                                                         if (res)
764                                                                 ast_log(LOG_WARNING, "Unable to set read format to %d\n", ast_best_codec(chan->nativeformats));
765                                                 }
766                                                 if (!res) {
767                                                         ast_set_write_format(chan, ast_best_codec(chan->nativeformats));
768                                                         if (res)
769                                                                 ast_log(LOG_WARNING, "Unable to set write format to %d\n", ast_best_codec(chan->nativeformats));
770                                                 }
771                                                 /* Check once more just in case */
772                                                 if (p->chan)
773                                                         res = -1;
774                                                 if (!res) {
775                                                         /* check if the moh class was changed with setmusiconhold */
776                                                         if (*(chan->musicclass))
777                                                                 strncpy(p->moh, chan->musicclass, sizeof(p->moh) - 1);
778                                                         ast_moh_start(chan, p->moh);
779                                                         manager_event(EVENT_FLAG_AGENT, "Agentlogin",
780                                                                 "Agent: %s\r\n"
781                                                                 "Channel: %s\r\n",
782                                                                 p->agent, chan->name);
783                                                         if (option_verbose > 2)
784                                                                 ast_verbose(VERBOSE_PREFIX_3 "Agent '%s' logged in (format %d/%d)\n", p->agent,
785                                                                                                 chan->readformat, chan->writeformat);
786                                                         /* Login this channel and wait for it to
787                                                            go away */
788                                                         p->chan = chan;
789                                                         check_availability(p, 0);
790                                                         ast_pthread_mutex_unlock(&p->lock);
791                                                         ast_pthread_mutex_unlock(&agentlock);
792                                                         while (res >= 0) {
793                                                                 ast_pthread_mutex_lock(&p->lock);
794                                                                 if (p->chan != chan)
795                                                                         res = -1;
796                                                                 ast_pthread_mutex_unlock(&p->lock);
797                                                                 /* Yield here so other interested threads can kick in. */
798                                                                 sched_yield();
799                                                                 if (res)
800                                                                         break;
801
802                                                                 /*      Synchronize channel ownership between call to agent and itself. */
803                                                                 pthread_mutex_lock( &p->app_lock );
804                                                                 ast_pthread_mutex_lock(&p->lock);
805                                                                 p->owning_app = pthread_self();
806                                                                 ast_pthread_mutex_unlock(&p->lock);
807                                                                 res = ast_safe_sleep_conditional( chan, 1000,
808                                                                                                                 agent_cont_sleep, p );
809                                                                 pthread_mutex_unlock( &p->app_lock );
810                                                                 sched_yield();
811                                                         }
812                                                         ast_pthread_mutex_lock(&p->lock);
813                                                         if (res && p->owner) 
814                                                                 ast_log(LOG_WARNING, "Huh?  We broke out when there was still an owner?\n");
815                                                         /* Log us off if appropriate */
816                                                         if (p->chan == chan)
817                                                                 p->chan = NULL;
818                                                         ast_pthread_mutex_unlock(&p->lock);
819                                                         if (option_verbose > 2)
820                                                                 ast_verbose(VERBOSE_PREFIX_3 "Agent '%s' logged out\n", p->agent);
821                                                         manager_event(EVENT_FLAG_AGENT, "Agentlogoff",
822                                                                 "Agent: %s\r\n",
823                                                                 p->agent);
824                                                         /* If there is no owner, go ahead and kill it now */
825                                                         if (p->dead && !p->owner)
826                                                                 free(p);
827                                                 }
828                                                 else {
829                                                         ast_pthread_mutex_unlock(&p->lock);
830                                                         p = NULL;
831                                                 }
832                                                 res = -1;
833                                         } else {
834                                                 ast_pthread_mutex_unlock(&p->lock);
835                                                 errmsg = "agent-alreadyon";
836                                                 p = NULL;
837                                         }
838                                         break;
839                         }
840                         ast_pthread_mutex_unlock(&p->lock);
841                         p = p->next;
842                 }
843                 if (!p)
844                         ast_pthread_mutex_unlock(&agentlock);
845
846                 if (!res)
847                         res = ast_app_getdata(chan, errmsg, user, sizeof(user) - 1, 0);
848         }
849                 
850         LOCAL_USER_REMOVE(u);
851         /* Always hangup */
852         return -1;
853 }
854
855
856 int load_module()
857 {
858         /* Make sure we can register our sip channel type */
859         if (ast_channel_register(type, tdesc, capability, agent_request)) {
860                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
861                 return -1;
862         }
863         ast_register_application(app, login_exec, synopsis, descrip);
864         ast_cli_register(&cli_show_agents);
865         /* Read in the config */
866         read_agent_config();
867         return 0;
868 }
869
870 int reload()
871 {
872         read_agent_config();
873         return 0;
874 }
875
876 int unload_module()
877 {
878         struct agent_pvt *p;
879         /* First, take us out of the channel loop */
880         ast_cli_unregister(&cli_show_agents);
881         ast_unregister_application(app);
882         ast_channel_unregister(type);
883         if (!ast_pthread_mutex_lock(&agentlock)) {
884                 /* Hangup all interfaces if they have an owner */
885                 p = agents;
886                 while(p) {
887                         if (p->owner)
888                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
889                         p = p->next;
890                 }
891                 agents = NULL;
892                 ast_pthread_mutex_unlock(&agentlock);
893         } else {
894                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
895                 return -1;
896         }               
897         return 0;
898 }
899
900 int usecount()
901 {
902         int res;
903         ast_pthread_mutex_lock(&usecnt_lock);
904         res = usecnt;
905         ast_pthread_mutex_unlock(&usecnt_lock);
906         return res;
907 }
908
909 char *key()
910 {
911         return ASTERISK_GPL_KEY;
912 }
913
914 char *description()
915 {
916         return desc;
917 }
918