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