Don't retry lock if there is no channel
[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                         if (p->chan) {
442                                 ast_queue_frame(p->chan, &null_frame, 1);
443                                 ast_pthread_mutex_unlock(&p->lock);     /* For other thread to read the condition. */
444                                 ast_pthread_mutex_lock(&p->app_lock);
445                                 ast_pthread_mutex_lock(&p->lock);
446                         }
447                         if( !p->chan )
448                         {
449                                 ast_log(LOG_WARNING, "Agent disconnected while we were connecting the call\n");
450                                 p->owner = NULL;
451                                 tmp->pvt->pvt = NULL;
452                                 p->app_sleep_cond = 1;
453                                 ast_channel_free( tmp );
454                                 return NULL;
455                         }
456                 }
457                 p->owning_app = pthread_self();
458                 /* After the above step, there should not be any blockers. */
459                 if (p->chan) {
460                         if (p->chan->blocking) {
461                                 ast_log( LOG_ERROR, "A blocker exists after agent channel ownership acquired\n" );
462                                 CRASH;
463                         }
464                         ast_moh_stop(p->chan);
465                 }
466         } else
467                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
468         return tmp;
469 }
470
471
472 static int read_agent_config(void)
473 {
474         struct ast_config *cfg;
475         struct ast_variable *v;
476         struct agent_pvt *p, *pl, *pn;
477         group = 0;
478         cfg = ast_load(config);
479         if (!cfg) {
480                 ast_log(LOG_NOTICE, "No agent configuration found -- agent support disabled\n");
481                 return 0;
482         }
483         ast_pthread_mutex_lock(&agentlock);
484         p = agents;
485         while(p) {
486                 p->dead = 1;
487                 p = p->next;
488         }
489         strcpy(moh, "default");
490         v = ast_variable_browse(cfg, "agents");
491         while(v) {
492                 /* Create the interface list */
493                 if (!strcasecmp(v->name, "agent")) {
494                         add_agent(v->value, 0);
495                 } else if (!strcasecmp(v->name, "group")) {
496                         group = ast_get_group(v->value);
497                 } else if (!strcasecmp(v->name, "musiconhold")) {
498                         strncpy(moh, v->value, sizeof(moh) - 1);
499                 }
500                 v = v->next;
501         }
502         p = agents;
503         pl = NULL;
504         while(p) {
505                 pn = p->next;
506                 if (p->dead) {
507                         /* Unlink */
508                         if (pl)
509                                 pl->next = p->next;
510                         else
511                                 agents = p->next;
512                         /* Destroy if  appropriate */
513                         if (!p->owner) {
514                                 if (!p->chan) {
515                                         free(p);
516                                 } else {
517                                         /* Cause them to hang up */
518                                         ast_softhangup(p->chan, AST_SOFTHANGUP_EXPLICIT);
519                                 }
520                         }
521                 } else
522                         pl = p;
523                 p = pn;
524         }
525         ast_pthread_mutex_unlock(&agentlock);
526         ast_destroy(cfg);
527         return 0;
528 }
529
530 static int check_availability(struct agent_pvt *newlyavailable, int needlock)
531 {
532         struct ast_channel *chan=NULL, *parent=NULL;
533         struct agent_pvt *p;
534         int res;
535         ast_log(LOG_DEBUG, "Checking availability of '%s'\n", newlyavailable->agent);
536         if (needlock)
537                 ast_pthread_mutex_lock(&agentlock);
538         p = agents;
539         while(p) {
540                 if (p == newlyavailable) {
541                         p = p->next;
542                         continue;
543                 }
544                 ast_pthread_mutex_lock(&p->lock);
545                 if (p->pending && ((p->group && (newlyavailable->group & p->group)) || !strcmp(p->agent, newlyavailable->agent))) {
546                         ast_log(LOG_DEBUG, "Call '%s' looks like a winner for agent '%s'\n", p->owner->name, newlyavailable->agent);
547                         /* We found a pending call, time to merge */
548                         chan = agent_new(newlyavailable, AST_STATE_DOWN);
549                         parent = p->owner;
550                         ast_pthread_mutex_unlock(&p->lock);
551                         break;
552                 }
553                 ast_pthread_mutex_unlock(&p->lock);
554                 p = p->next;
555         }
556         if (needlock)
557                 ast_pthread_mutex_unlock(&agentlock);
558         if (parent && chan)  {
559                 ast_log( LOG_DEBUG, "Playing beep, lang '%s'\n", newlyavailable->chan->language);
560                 res = ast_streamfile(newlyavailable->chan, "beep", newlyavailable->chan->language);
561                 ast_log( LOG_DEBUG, "Played beep, result '%d'\n", res);
562                 if (!res) {
563                         res = ast_waitstream(newlyavailable->chan, "");
564                         ast_log( LOG_DEBUG, "Waited for stream, result '%d'\n", res);
565                 }
566                 if (!res) {
567                         ast_setstate(parent, AST_STATE_UP);
568                         ast_setstate(chan, AST_STATE_UP);
569                         ast_channel_masquerade(parent, chan);
570                         ast_hangup(chan);
571                 } else {
572                         ast_log(LOG_NOTICE, "Not sure this will always work..\n");
573                         ast_hangup(chan);
574                 }
575         }
576         return 0;
577 }
578
579 static struct ast_channel *agent_request(char *type, int format, void *data)
580 {
581         struct agent_pvt *p;
582         struct ast_channel *chan = NULL;
583         char *s;
584         unsigned int groupmatch;
585         int waitforagent=0;
586         s = data;
587         if ((s[0] == '@') && (sscanf(s + 1, "%d", &groupmatch) == 1)) {
588                 groupmatch = (1 << groupmatch);
589         } else if ((s[0] == ':') && (sscanf(s + 1, "%d", &groupmatch) == 1)) {
590                 groupmatch = (1 << groupmatch);
591                 waitforagent = 1;
592         } else {
593                 groupmatch = 0;
594         }
595         ast_pthread_mutex_lock(&agentlock);
596         p = agents;
597         while(p) {
598                 ast_pthread_mutex_lock(&p->lock);
599                 if (!p->pending && ((groupmatch && (p->group & groupmatch)) || !strcmp(data, p->agent))) {
600                         /* Agent must be registered, but not have any active call */
601                         if (!p->owner && p->chan) {
602                                 chan = agent_new(p, AST_STATE_DOWN);
603                         }
604                         ast_pthread_mutex_unlock(&p->lock);
605                         break;
606                 }
607                 ast_pthread_mutex_unlock(&p->lock);
608                 p = p->next;
609         }
610         if (!chan && waitforagent) {
611                 /* No agent available -- but we're requesting to wait for one.
612                    Allocate a place holder */
613                 ast_log(LOG_DEBUG, "Creating place holder for '%s'\n", s);
614                 p = add_agent(data, 1);
615                 p->group = groupmatch;
616                 chan = agent_new(p, AST_STATE_DOWN);
617                 if (!chan) {
618                         ast_log(LOG_WARNING, "Weird...  Fix this to drop the unused pending agent\n");
619                 }
620         }
621         ast_pthread_mutex_unlock(&agentlock);
622         return chan;
623 }
624
625 static int powerof(unsigned int v)
626 {
627         int x;
628         for (x=0;x<32;x++) {
629                 if (v & (1 << x)) return x;
630         }
631         return 0;
632 }
633
634 static int agents_show(int fd, int argc, char **argv)
635 {
636         struct agent_pvt *p;
637         char username[256];
638         char location[256];
639         char talkingto[256];
640
641         if (argc != 2)
642                 return RESULT_SHOWUSAGE;
643         ast_pthread_mutex_lock(&agentlock);
644         p = agents;
645         while(p) {
646                 ast_pthread_mutex_lock(&p->lock);
647                 if (p->pending) {
648                         if (p->group)
649                                 ast_cli(fd, "-- Pending call to group %d\n", powerof(p->group));
650                         else
651                                 ast_cli(fd, "-- Pending call to agent %s\n", p->agent);
652                 } else {
653                         if (strlen(p->name))
654                                 snprintf(username, sizeof(username), "(%s) ", p->name);
655                         else
656                                 strcpy(username, "");
657                         if (p->chan) {
658                                 snprintf(location, sizeof(location), "logged in on %s", p->chan->name);
659                                 if (p->owner && p->owner->bridge) {
660                                         snprintf(talkingto, sizeof(talkingto), " talking to %s", p->owner->bridge->name);
661                                 } else {
662                                         strcpy(talkingto, " is idle");
663                                 }
664                         } else {
665                                 strcpy(location, "not logged in");
666                                 strcpy(talkingto, "");
667                         }
668                         ast_cli(fd, "%-12.12s %s%s%s\n", p->agent, 
669                                         username, location, talkingto);
670                 }
671                 ast_pthread_mutex_unlock(&p->lock);
672                 p = p->next;
673         }
674         ast_pthread_mutex_unlock(&agentlock);
675         return RESULT_SUCCESS;
676 }
677
678 static char show_agents_usage[] = 
679 "Usage: show agents\n"
680 "       Provides summary information on agents.\n";
681
682 static struct ast_cli_entry cli_show_agents = {
683         { "show", "agents", NULL }, agents_show, 
684         "Show status of agents", show_agents_usage, NULL };
685
686 STANDARD_LOCAL_USER;
687 LOCAL_USER_DECL;
688
689 static int login_exec(struct ast_channel *chan, void *data)
690 {
691         int res=0;
692         int tries = 0;
693         struct agent_pvt *p;
694         struct localuser *u;
695         char user[AST_MAX_AGENT];
696         char pass[AST_MAX_AGENT];
697         char xpass[AST_MAX_AGENT] = "";
698         char *errmsg;
699         char info[512];
700         char *opt_user = NULL;
701         char *options = NULL;
702         int play_announcement;
703         
704         LOCAL_USER_ADD(u);
705
706         /* Parse the arguments XXX Check for failure XXX */
707         strncpy(info, (char *)data, strlen((char *)data) + AST_MAX_EXTENSION-1);
708         opt_user = info;
709         if( opt_user ) {
710                 options = strchr(opt_user, '|');
711                 if (options) {
712                         *options = '\0';
713                         options++;
714                 }
715         }
716
717         if (chan->_state != AST_STATE_UP)
718                 res = ast_answer(chan);
719         if (!res) {
720                 if( opt_user && strlen(opt_user))
721                         strncpy( user, opt_user, AST_MAX_AGENT );
722                 else
723                         res = ast_app_getdata(chan, "agent-user", user, sizeof(user) - 1, 0);
724         }
725         while (!res && (tries < 3)) {
726                 /* Check for password */
727                 ast_pthread_mutex_lock(&agentlock);
728                 p = agents;
729                 while(p) {
730                         if (!strcmp(p->agent, user) && !p->pending)
731                                 strncpy(xpass, p->password, sizeof(xpass) - 1);
732                         p = p->next;
733                 }
734                 ast_pthread_mutex_unlock(&agentlock);
735                 if (!res) {
736                         if (strlen(xpass))
737                                 res = ast_app_getdata(chan, "agent-pass", pass, sizeof(pass) - 1, 0);
738                         else
739                                 strcpy(pass, "");
740                 }
741                 errmsg = "agent-incorrect";
742
743 #if 0
744                 ast_log(LOG_NOTICE, "user: %s, pass: %s\n", user, pass);
745 #endif          
746
747                 /* Check again for accuracy */
748                 ast_pthread_mutex_lock(&agentlock);
749                 p = agents;
750                 while(p) {
751                         ast_pthread_mutex_lock(&p->lock);
752                         if (!strcmp(p->agent, user) &&
753                                 !strcmp(p->password, pass) && !p->pending) {
754                                         if (!p->chan) {
755                                                 play_announcement = 1;
756                                                 if( options )
757                                                         if( strchr( options, 's' ) )
758                                                                 play_announcement = 0;
759                                                 if( play_announcement )
760                                                         res = ast_streamfile(chan, "agent-loginok", chan->language);
761                                                 if (!res)
762                                                         ast_waitstream(chan, "");
763                                                 if (!res) {
764                                                         res = ast_set_read_format(chan, ast_best_codec(chan->nativeformats));
765                                                         if (res)
766                                                                 ast_log(LOG_WARNING, "Unable to set read format to %d\n", ast_best_codec(chan->nativeformats));
767                                                 }
768                                                 if (!res) {
769                                                         ast_set_write_format(chan, ast_best_codec(chan->nativeformats));
770                                                         if (res)
771                                                                 ast_log(LOG_WARNING, "Unable to set write format to %d\n", ast_best_codec(chan->nativeformats));
772                                                 }
773                                                 /* Check once more just in case */
774                                                 if (p->chan)
775                                                         res = -1;
776                                                 if (!res) {
777                                                         /* check if the moh class was changed with setmusiconhold */
778                                                         if (*(chan->musicclass))
779                                                                 strncpy(p->moh, chan->musicclass, sizeof(p->moh) - 1);
780                                                         ast_moh_start(chan, p->moh);
781                                                         manager_event(EVENT_FLAG_AGENT, "Agentlogin",
782                                                                 "Agent: %s\r\n"
783                                                                 "Channel: %s\r\n",
784                                                                 p->agent, chan->name);
785                                                         if (option_verbose > 2)
786                                                                 ast_verbose(VERBOSE_PREFIX_3 "Agent '%s' logged in (format %d/%d)\n", p->agent,
787                                                                                                 chan->readformat, chan->writeformat);
788                                                         /* Login this channel and wait for it to
789                                                            go away */
790                                                         p->chan = chan;
791                                                         check_availability(p, 0);
792                                                         ast_pthread_mutex_unlock(&p->lock);
793                                                         ast_pthread_mutex_unlock(&agentlock);
794                                                         while (res >= 0) {
795                                                                 ast_pthread_mutex_lock(&p->lock);
796                                                                 if (p->chan != chan)
797                                                                         res = -1;
798                                                                 ast_pthread_mutex_unlock(&p->lock);
799                                                                 /* Yield here so other interested threads can kick in. */
800                                                                 sched_yield();
801                                                                 if (res)
802                                                                         break;
803
804                                                                 /*      Synchronize channel ownership between call to agent and itself. */
805                                                                 pthread_mutex_lock( &p->app_lock );
806                                                                 ast_pthread_mutex_lock(&p->lock);
807                                                                 p->owning_app = pthread_self();
808                                                                 ast_pthread_mutex_unlock(&p->lock);
809                                                                 res = ast_safe_sleep_conditional( chan, 1000,
810                                                                                                                 agent_cont_sleep, p );
811                                                                 pthread_mutex_unlock( &p->app_lock );
812                                                                 sched_yield();
813                                                         }
814                                                         ast_pthread_mutex_lock(&p->lock);
815                                                         if (res && p->owner) 
816                                                                 ast_log(LOG_WARNING, "Huh?  We broke out when there was still an owner?\n");
817                                                         /* Log us off if appropriate */
818                                                         if (p->chan == chan)
819                                                                 p->chan = NULL;
820                                                         ast_pthread_mutex_unlock(&p->lock);
821                                                         if (option_verbose > 2)
822                                                                 ast_verbose(VERBOSE_PREFIX_3 "Agent '%s' logged out\n", p->agent);
823                                                         manager_event(EVENT_FLAG_AGENT, "Agentlogoff",
824                                                                 "Agent: %s\r\n",
825                                                                 p->agent);
826                                                         /* If there is no owner, go ahead and kill it now */
827                                                         if (p->dead && !p->owner)
828                                                                 free(p);
829                                                 }
830                                                 else {
831                                                         ast_pthread_mutex_unlock(&p->lock);
832                                                         p = NULL;
833                                                 }
834                                                 res = -1;
835                                         } else {
836                                                 ast_pthread_mutex_unlock(&p->lock);
837                                                 errmsg = "agent-alreadyon";
838                                                 p = NULL;
839                                         }
840                                         break;
841                         }
842                         ast_pthread_mutex_unlock(&p->lock);
843                         p = p->next;
844                 }
845                 if (!p)
846                         ast_pthread_mutex_unlock(&agentlock);
847
848                 if (!res)
849                         res = ast_app_getdata(chan, errmsg, user, sizeof(user) - 1, 0);
850         }
851                 
852         LOCAL_USER_REMOVE(u);
853         /* Always hangup */
854         return -1;
855 }
856
857
858 int load_module()
859 {
860         /* Make sure we can register our sip channel type */
861         if (ast_channel_register(type, tdesc, capability, agent_request)) {
862                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
863                 return -1;
864         }
865         ast_register_application(app, login_exec, synopsis, descrip);
866         ast_cli_register(&cli_show_agents);
867         /* Read in the config */
868         read_agent_config();
869         return 0;
870 }
871
872 int reload()
873 {
874         read_agent_config();
875         return 0;
876 }
877
878 int unload_module()
879 {
880         struct agent_pvt *p;
881         /* First, take us out of the channel loop */
882         ast_cli_unregister(&cli_show_agents);
883         ast_unregister_application(app);
884         ast_channel_unregister(type);
885         if (!ast_pthread_mutex_lock(&agentlock)) {
886                 /* Hangup all interfaces if they have an owner */
887                 p = agents;
888                 while(p) {
889                         if (p->owner)
890                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
891                         p = p->next;
892                 }
893                 agents = NULL;
894                 ast_pthread_mutex_unlock(&agentlock);
895         } else {
896                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
897                 return -1;
898         }               
899         return 0;
900 }
901
902 int usecount()
903 {
904         int res;
905         ast_pthread_mutex_lock(&usecnt_lock);
906         res = usecnt;
907         ast_pthread_mutex_unlock(&usecnt_lock);
908         return res;
909 }
910
911 char *key()
912 {
913         return ASTERISK_GPL_KEY;
914 }
915
916 char *description()
917 {
918         return desc;
919 }
920