d293f9cc13612d16ce6a8dc38707f0959a2d459b
[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][|[options][exten]@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 static int wrapuptime;
81 static int ackcall;
82
83 static int usecnt =0;
84 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
85
86 /* Protect the interface list (of sip_pvt's) */
87 static ast_mutex_t agentlock = AST_MUTEX_INITIALIZER;
88
89 static struct agent_pvt {
90         ast_mutex_t lock;                               /* Channel private lock */
91         int dead;                                                       /* Poised for destruction? */
92         int pending;                                            /* Not a real agent -- just pending a match */
93         int abouttograb;                                        /* About to grab */
94         int autologoff;                                 /* Auto timeout time */
95         int ackcall;                                    /* ackcall */
96         time_t start;                                           /* When call started */
97         struct timeval lastdisc;                        /* When last disconnected */
98         int wrapuptime;                                         /* Wrapup time in ms */
99         unsigned int group;                                     /* Group memberships */
100         int acknowledged;                                       /* Acknowledged */
101         char moh[80];                                           /* Which music on hold */
102         char agent[AST_MAX_AGENT];                      /* Agent ID */
103         char password[AST_MAX_AGENT];           /* Password for Agent login */
104         char name[AST_MAX_AGENT];
105         ast_mutex_t app_lock;                   /* Synchronization between owning applications */
106         volatile pthread_t owning_app;          /* Owning application thread id */
107         volatile int app_sleep_cond;            /* Sleep condition for the login app */
108         struct ast_channel *owner;                      /* Agent */
109         char loginchan[80];
110         struct ast_channel *chan;                       /* Channel we use */
111         struct agent_pvt *next;                         /* Agent */
112 } *agents = NULL;
113
114 #define CHECK_FORMATS(ast, p) do { \
115         if (p->chan) {\
116                 if (ast->nativeformats != p->chan->nativeformats) { \
117                         ast_log(LOG_DEBUG, "Native formats changing from %d to %d\n", ast->nativeformats, p->chan->nativeformats); \
118                         /* Native formats changed, reset things */ \
119                         ast->nativeformats = p->chan->nativeformats; \
120                         ast_log(LOG_DEBUG, "Resetting read to %d and write to %d\n", ast->readformat, ast->writeformat);\
121                         ast_set_read_format(ast, ast->readformat); \
122                         ast_set_write_format(ast, ast->writeformat); \
123                 } \
124                 if (p->chan->readformat != ast->pvt->rawreadformat)  \
125                         ast_set_read_format(p->chan, ast->pvt->rawreadformat); \
126                 if (p->chan->writeformat != ast->pvt->rawwriteformat) \
127                         ast_set_write_format(p->chan, ast->pvt->rawwriteformat); \
128         } \
129 } while(0)
130
131 /* Cleanup moves all the relevant FD's from the 2nd to the first, but retains things
132    properly for a timingfd XXX This might need more work if agents were logged in as agents or other
133    totally impractical combinations XXX */
134
135 #define CLEANUP(ast, p) do { \
136         int x; \
137         if (p->chan) { \
138                 for (x=0;x<AST_MAX_FDS;x++) {\
139                         if (x != AST_MAX_FDS - 2) \
140                                 ast->fds[x] = p->chan->fds[x]; \
141                 } \
142                 ast->fds[AST_MAX_FDS - 3] = p->chan->fds[AST_MAX_FDS - 2]; \
143         } \
144 } while(0)
145
146
147 static void agent_unlink(struct agent_pvt *agent)
148 {
149         struct agent_pvt *p, *prev;
150         prev = NULL;
151         p = agents;
152         while(p) {
153                 if (p == agent) {
154                         if (prev)
155                                 prev->next = agent->next;
156                         else
157                                 agents = agent->next;
158                         break;
159                 }
160                 prev = p;
161                 p = p->next;
162         }
163 }
164
165 static struct agent_pvt *add_agent(char *agent, int pending)
166 {
167         char tmp[256];
168         char *password=NULL, *name=NULL;
169         struct agent_pvt *p, *prev;
170         
171         strncpy(tmp, agent, sizeof(tmp));
172         if ((password = strchr(tmp, ','))) {
173                 *password = '\0';
174                 password++;
175                 while (*password < 33) password++;
176         }
177         if (password && (name = strchr(password, ','))) {
178                 *name = '\0';
179                 name++;
180                 while (*name < 33) name++; 
181         }
182         prev=NULL;
183         p = agents;
184         while(p) {
185                 if (!pending && !strcmp(p->agent, tmp))
186                         break;
187                 prev = p;
188                 p = p->next;
189         }
190         if (!p) {
191                 p = malloc(sizeof(struct agent_pvt));
192                 if (p) {
193                         memset(p, 0, sizeof(struct agent_pvt));
194                         strncpy(p->agent, tmp, sizeof(p->agent) -1);
195                         ast_mutex_init( &p->lock );
196                         ast_mutex_init( &p->app_lock );
197                         p->owning_app = -1;
198                         p->app_sleep_cond = 1;
199                         p->group = group;
200                         p->pending = pending;
201                         p->next = NULL;
202                         if (prev)
203                                 prev->next = p;
204                         else
205                                 agents = p;
206                         
207                 }
208         }
209         if (!p)
210                 return NULL;
211         strncpy(p->password, password ? password : "", sizeof(p->password) - 1);
212         strncpy(p->name, name ? name : "", sizeof(p->name) - 1);
213         strncpy(p->moh, moh, sizeof(p->moh) - 1);
214         p->ackcall = ackcall;
215         p->autologoff = autologoff;
216         p->wrapuptime = wrapuptime;
217         if (pending)
218                 p->dead = 1;
219         else
220                 p->dead = 0;
221         return p;
222 }
223
224 static int agent_cleanup(struct agent_pvt *p)
225 {
226         struct ast_channel *chan = p->owner;
227         p->owner = NULL;
228         chan->pvt->pvt = NULL;
229         p->app_sleep_cond = 1;
230         /* Release ownership of the agent to other threads (presumably running the login app). */
231         ast_mutex_unlock(&p->app_lock);
232         if (chan)
233                 ast_channel_free(chan);
234         if (p->dead)
235                 free(p);
236         return 0;
237 }
238
239 static int check_availability(struct agent_pvt *newlyavailable, int needlock);
240
241 static int agent_answer(struct ast_channel *ast)
242 {
243         ast_log(LOG_WARNING, "Huh?  Agent is being asked to answer?\n");
244         return -1;
245 }
246
247 static struct ast_frame  *agent_read(struct ast_channel *ast)
248 {
249         struct agent_pvt *p = ast->pvt->pvt;
250         struct ast_frame *f = NULL;
251         static struct ast_frame null_frame = { AST_FRAME_NULL, };
252         static struct ast_frame answer_frame = { AST_FRAME_CONTROL, AST_CONTROL_ANSWER };
253         ast_mutex_lock(&p->lock); 
254         CHECK_FORMATS(ast, p);
255         if (p->chan) {
256                 p->chan->exception = ast->exception;
257                 if (ast->fdno == AST_MAX_FDS - 3)
258                         p->chan->fdno = AST_MAX_FDS - 2;
259                 else
260                         p->chan->fdno = ast->fdno;
261                 f = ast_read(p->chan);
262         } else
263                 f = &null_frame;
264         if (!f) {
265                 /* If there's a channel, hang it up  (if it's on a callback) make it NULL */
266                 if (p->chan) {
267                         /* Note that we don't hangup if it's not a callback because Asterisk will do it
268                            for us when the PBX instance that called login finishes */
269                         if (strlen(p->loginchan))
270                                 ast_hangup(p->chan);
271                         p->chan = NULL;
272                         p->acknowledged = 0;
273                 }
274         }
275         if (f && (f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
276 /* TC */
277                 if (p->ackcall) {
278                         if (option_verbose > 2)
279                                 ast_verbose(VERBOSE_PREFIX_3 "%s answered, waiting for '#' to acknowledge\n", p->chan->name);
280                         /* Don't pass answer along */
281                         ast_frfree(f);
282                         f = &null_frame;
283                 }
284         else {
285                         p->acknowledged = 1;
286                         f = &answer_frame;
287         }
288         }
289         if (f && (f->frametype == AST_FRAME_DTMF) && (f->subclass == '#')) {
290                 if (!p->acknowledged) {
291                         if (option_verbose > 2)
292                                 ast_verbose(VERBOSE_PREFIX_3 "%s acknowledged\n", p->chan->name);
293                         p->acknowledged = 1;
294                         ast_frfree(f);
295                         f = &answer_frame;
296                 }
297         }
298         if (f && (f->frametype == AST_FRAME_DTMF) && (f->subclass == '*')) {
299                 /* * terminates call */
300                 ast_frfree(f);
301                 f = NULL;
302         }
303         CLEANUP(ast,p);
304         ast_mutex_unlock(&p->lock);
305         return f;
306 }
307
308 static int agent_write(struct ast_channel *ast, struct ast_frame *f)
309 {
310         struct agent_pvt *p = ast->pvt->pvt;
311         int res = -1;
312         CHECK_FORMATS(ast, p);
313         ast_mutex_lock(&p->lock);
314         if (p->chan) {
315                 if ((f->frametype != AST_FRAME_VOICE) ||
316                         (f->subclass == p->chan->writeformat)) {
317                         res = ast_write(p->chan, f);
318                 } else {
319                         ast_log(LOG_DEBUG, "Dropping one incompatible voice frame on '%s' to '%s'\n", ast->name, p->chan->name);
320                         res = 0;
321                 }
322         } else
323                 res = 0;
324         CLEANUP(ast, p);
325         ast_mutex_unlock(&p->lock);
326         return res;
327 }
328
329 static int agent_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
330 {
331         struct agent_pvt *p = newchan->pvt->pvt;
332         ast_mutex_lock(&p->lock);
333         if (p->owner != oldchan) {
334                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
335                 ast_mutex_unlock(&p->lock);
336                 return -1;
337         }
338         p->owner = newchan;
339         ast_mutex_unlock(&p->lock);
340         return 0;
341 }
342
343 static int agent_indicate(struct ast_channel *ast, int condition)
344 {
345         struct agent_pvt *p = ast->pvt->pvt;
346         int res = -1;
347         ast_mutex_lock(&p->lock);
348         if (p->chan)
349                 res = ast_indicate(p->chan, condition);
350         else
351                 res = 0;
352         ast_mutex_unlock(&p->lock);
353         return res;
354 }
355
356 static int agent_digit(struct ast_channel *ast, char digit)
357 {
358         struct agent_pvt *p = ast->pvt->pvt;
359         int res = -1;
360         ast_mutex_lock(&p->lock);
361         if (p->chan)
362                 res = p->chan->pvt->send_digit(p->chan, digit);
363         else
364                 res = 0;
365         ast_mutex_unlock(&p->lock);
366         return res;
367 }
368
369 static int agent_call(struct ast_channel *ast, char *dest, int timeout)
370 {
371         struct agent_pvt *p = ast->pvt->pvt;
372         int res = -1;
373         ast_mutex_lock(&p->lock);
374         p->acknowledged = 0;
375         if (!p->chan) {
376                 if (p->pending) {
377                         ast_log(LOG_DEBUG, "Pretending to dial on pending agent\n");
378                         ast_setstate(ast, AST_STATE_DIALING);
379                         res = 0;
380                 } else {
381                         ast_log(LOG_NOTICE, "Whoa, they hung up between alloc and call...  what are the odds of that?\n");
382                         res = -1;
383                 }
384                 ast_mutex_unlock(&p->lock);
385                 return res;
386         } else if (strlen(p->loginchan)) {
387                 time(&p->start);
388                 /* Call on this agent */
389                 if (option_verbose > 2)
390                         ast_verbose(VERBOSE_PREFIX_3 "outgoing agentcall, to agent '%s', on '%s'\n", p->agent, p->chan->name);
391                 if (p->chan->callerid)
392                         free(p->chan->callerid);
393                 if (ast->callerid)
394                         p->chan->callerid = strdup(ast->callerid);
395                 else
396                         p->chan->callerid = NULL;
397                 res = ast_call(p->chan, p->loginchan, 0);
398                 CLEANUP(ast,p);
399                 ast_mutex_unlock(&p->lock);
400                 return res;
401         }
402         ast_verbose( VERBOSE_PREFIX_3 "agent_call, call to agent '%s' call on '%s'\n", p->agent, p->chan->name);
403         ast_log( LOG_DEBUG, "Playing beep, lang '%s'\n", p->chan->language);
404         res = ast_streamfile(p->chan, "beep", p->chan->language);
405         ast_log( LOG_DEBUG, "Played beep, result '%d'\n", res);
406         if (!res) {
407                 res = ast_waitstream(p->chan, "");
408                 ast_log( LOG_DEBUG, "Waited for stream, result '%d'\n", res);
409         }
410         if (!res) {
411                 res = ast_set_read_format(p->chan, ast_best_codec(p->chan->nativeformats));
412                 ast_log( LOG_DEBUG, "Set read format, result '%d'\n", res);
413                 if (res)
414                         ast_log(LOG_WARNING, "Unable to set read format to %s\n", ast_getformatname(ast_best_codec(p->chan->nativeformats)));
415         } else {
416                 // Agent hung-up
417                 p->chan = NULL;
418         }
419
420         if (!res) {
421                 ast_set_write_format(p->chan, ast_best_codec(p->chan->nativeformats));
422                 ast_log( LOG_DEBUG, "Set write format, result '%d'\n", res);
423                 if (res)
424                         ast_log(LOG_WARNING, "Unable to set write format to %s\n", ast_getformatname(ast_best_codec(p->chan->nativeformats)));
425         }
426         if( !res )
427         {
428                 /* Call is immediately up, or might need ack */
429                 if (p->ackcall > 1)
430                         ast_setstate(ast, AST_STATE_RINGING);
431                 else {
432                         ast_setstate(ast, AST_STATE_UP);
433                         p->acknowledged = 1;
434                 }
435                 res = 0;
436         }
437         CLEANUP(ast,p);
438         ast_mutex_unlock(&p->lock);
439         return res;
440 }
441
442 static int agent_hangup(struct ast_channel *ast)
443 {
444         struct agent_pvt *p = ast->pvt->pvt;
445         int howlong = 0;
446         ast_mutex_lock(&p->lock);
447         p->owner = NULL;
448         ast->pvt->pvt = NULL;
449         p->app_sleep_cond = 1;
450         p->acknowledged = 0;
451         if (p->start && (ast->_state != AST_STATE_UP))
452                 howlong = time(NULL) - p->start;
453         time(&p->start);
454         if (p->chan) {
455                 /* If they're dead, go ahead and hang up on the agent now */
456                 if (strlen(p->loginchan)) {
457                         if (p->chan) {
458                                 /* Recognize the hangup and pass it along immediately */
459                                 ast_hangup(p->chan);
460                                 p->chan = NULL;
461                         }
462                         ast_log(LOG_DEBUG, "Hungup, howlong is %d, autologoff is %d\n", howlong, p->autologoff);
463                         if (howlong  && p->autologoff && (howlong > p->autologoff)) {
464                                 ast_log(LOG_NOTICE, "Agent '%s' didn't answer/confirm within %d seconds (waited %d)\n", p->name, p->autologoff, howlong);
465                                 strcpy(p->loginchan, "");
466                         }
467                 } else if (p->dead) {
468                         ast_mutex_lock(&p->chan->lock);
469                         ast_softhangup(p->chan, AST_SOFTHANGUP_EXPLICIT);
470                         ast_mutex_unlock(&p->chan->lock);
471                 } else {
472                         ast_mutex_lock(&p->chan->lock);
473                         ast_moh_start(p->chan, p->moh);
474                         ast_mutex_unlock(&p->chan->lock);
475                 }
476         }
477 #if 0
478                 ast_mutex_unlock(&p->lock);
479                 /* Release ownership of the agent to other threads (presumably running the login app). */
480                 ast_mutex_unlock(&p->app_lock);
481         } else if (p->dead) {
482                 /* Go ahead and lose it */
483                 ast_mutex_unlock(&p->lock);
484                 /* Release ownership of the agent to other threads (presumably running the login app). */
485                 ast_mutex_unlock(&p->app_lock);
486         } else {
487                 ast_mutex_unlock(&p->lock);
488                 /* Release ownership of the agent to other threads (presumably running the login app). */
489                 ast_mutex_unlock(&p->app_lock);
490         }
491 #endif  
492         ast_mutex_unlock(&p->lock);
493
494         if (p->pending) {
495                 ast_mutex_lock(&agentlock);
496                 agent_unlink(p);
497                 ast_mutex_unlock(&agentlock);
498         }
499         if (p->abouttograb) {
500                 /* Let the "about to grab" thread know this isn't valid anymore, and let it
501                    kill it later */
502                 p->abouttograb = 0;
503         } else if (p->dead) {
504                 free(p);
505         } else {
506                 if (p->chan) {
507                         /* Not dead -- check availability now */
508                         ast_mutex_lock(&p->lock);
509                         /* Store last disconnect time */
510                         gettimeofday(&p->lastdisc, NULL);
511                         ast_mutex_unlock(&p->lock);
512                 }
513                 /* Release ownership of the agent to other threads (presumably running the login app). */
514                 ast_mutex_unlock(&p->app_lock);
515         }
516         return 0;
517 }
518
519 static int agent_cont_sleep( void *data )
520 {
521         struct agent_pvt *p;
522         struct timeval tv;
523         int res;
524
525         p = (struct agent_pvt *)data;
526
527         ast_mutex_lock(&p->lock);
528         res = p->app_sleep_cond;
529         if (p->lastdisc.tv_sec) {
530                 gettimeofday(&tv, NULL);
531                 if ((tv.tv_sec - p->lastdisc.tv_sec) * 1000 + 
532                         (tv.tv_usec - p->lastdisc.tv_usec) / 1000 > p->wrapuptime) 
533                         res = 1;
534         }
535         ast_mutex_unlock(&p->lock);
536 #if 0
537         if( !res )
538                 ast_log( LOG_DEBUG, "agent_cont_sleep() returning %d\n", res );
539 #endif          
540         return res;
541 }
542
543 static int agent_ack_sleep( void *data )
544 {
545         struct agent_pvt *p;
546         int res=0;
547         int to = 1000;
548         struct ast_frame *f;
549
550         /* Wait a second and look for something */
551
552         p = (struct agent_pvt *)data;
553         if (p->chan) {
554                 for(;;) {
555                         to = ast_waitfor(p->chan, to);
556                         if (to < 0) {
557                                 res = -1;
558                                 break;
559                         }
560                         if (!to) {
561                                 res = 0;
562                                 break;
563                         }
564                         f = ast_read(p->chan);
565                         if (!f) {
566                                 res = -1;
567                                 break;
568                         }
569                         if (f->frametype == AST_FRAME_DTMF)
570                                 res = f->subclass;
571                         else
572                                 res = 0;
573                         ast_frfree(f);
574                         ast_mutex_lock(&p->lock);
575                         if (!p->app_sleep_cond) {
576                                 ast_mutex_unlock(&p->lock);
577                                 res = 0;
578                                 break;
579                         } else if (res == '#') {
580                                 ast_mutex_unlock(&p->lock);
581                                 res = 1;
582                                 break;
583                         }
584                         ast_mutex_unlock(&p->lock);
585                         res = 0;
586                 }
587         } else
588                 res = -1;
589         return res;
590 }
591
592 static struct ast_channel *agent_new(struct agent_pvt *p, int state)
593 {
594         struct ast_channel *tmp;
595         struct ast_frame null_frame = { AST_FRAME_NULL };
596 #if 0
597         if (!p->chan) {
598                 ast_log(LOG_WARNING, "No channel? :(\n");
599                 return NULL;
600         }
601 #endif  
602         tmp = ast_channel_alloc(0);
603         if (tmp) {
604                 if (p->chan) {
605                         tmp->nativeformats = p->chan->nativeformats;
606                         tmp->writeformat = p->chan->writeformat;
607                         tmp->pvt->rawwriteformat = p->chan->writeformat;
608                         tmp->readformat = p->chan->readformat;
609                         tmp->pvt->rawreadformat = p->chan->readformat;
610                         strncpy(tmp->language, p->chan->language, sizeof(tmp->language)-1);
611                         strncpy(tmp->context, p->chan->context, sizeof(tmp->context)-1);
612                         strncpy(tmp->exten, p->chan->exten, sizeof(tmp->exten)-1);
613                 } else {
614                         tmp->nativeformats = AST_FORMAT_SLINEAR;
615                         tmp->writeformat = AST_FORMAT_SLINEAR;
616                         tmp->pvt->rawwriteformat = AST_FORMAT_SLINEAR;
617                         tmp->readformat = AST_FORMAT_SLINEAR;
618                         tmp->pvt->rawreadformat = AST_FORMAT_SLINEAR;
619                 }
620                 if (p->pending)
621                         snprintf(tmp->name, sizeof(tmp->name), "Agent/P%s-%d", p->agent, rand() & 0xffff);
622                 else
623                         snprintf(tmp->name, sizeof(tmp->name), "Agent/%s", p->agent);
624                 tmp->type = type;
625                 ast_setstate(tmp, state);
626                 tmp->pvt->pvt = p;
627                 tmp->pvt->send_digit = agent_digit;
628                 tmp->pvt->call = agent_call;
629                 tmp->pvt->hangup = agent_hangup;
630                 tmp->pvt->answer = agent_answer;
631                 tmp->pvt->read = agent_read;
632                 tmp->pvt->write = agent_write;
633                 tmp->pvt->exception = agent_read;
634                 tmp->pvt->indicate = agent_indicate;
635                 tmp->pvt->fixup = agent_fixup;
636                 p->owner = tmp;
637                 ast_mutex_lock(&usecnt_lock);
638                 usecnt++;
639                 ast_mutex_unlock(&usecnt_lock);
640                 ast_update_use_count();
641                 tmp->priority = 1;
642                 /* Wake up and wait for other applications (by definition the login app)
643                  * to release this channel). Takes ownership of the agent channel
644                  * to this thread only.
645                  * For signalling the other thread, ast_queue_frame is used until we
646                  * can safely use signals for this purpose. The pselect() needs to be
647                  * implemented in the kernel for this.
648                  */
649                 p->app_sleep_cond = 0;
650                 if( ast_mutex_trylock(&p->app_lock) )
651                 {
652                         if (p->chan) {
653                                 ast_queue_frame(p->chan, &null_frame, 1);
654                                 ast_mutex_unlock(&p->lock);     /* For other thread to read the condition. */
655                                 ast_mutex_lock(&p->app_lock);
656                                 ast_mutex_lock(&p->lock);
657                         }
658                         if( !p->chan )
659                         {
660                                 ast_log(LOG_WARNING, "Agent disconnected while we were connecting the call\n");
661                                 p->owner = NULL;
662                                 tmp->pvt->pvt = NULL;
663                                 p->app_sleep_cond = 1;
664                                 ast_channel_free( tmp );
665                                 ast_mutex_unlock(&p->lock);     /* For other thread to read the condition. */
666                                 ast_mutex_unlock(&p->app_lock);
667                                 return NULL;
668                         }
669                 }
670                 p->owning_app = pthread_self();
671                 /* After the above step, there should not be any blockers. */
672                 if (p->chan) {
673                         if (p->chan->blocking) {
674                                 ast_log( LOG_ERROR, "A blocker exists after agent channel ownership acquired\n" );
675                                 CRASH;
676                         }
677                         ast_moh_stop(p->chan);
678                 }
679         } else
680                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
681         return tmp;
682 }
683
684
685 static int read_agent_config(void)
686 {
687         struct ast_config *cfg;
688         struct ast_variable *v;
689         struct agent_pvt *p, *pl, *pn;
690         group = 0;
691         autologoff = 0;
692         wrapuptime = 0;
693         ackcall = 1;
694         cfg = ast_load(config);
695         if (!cfg) {
696                 ast_log(LOG_NOTICE, "No agent configuration found -- agent support disabled\n");
697                 return 0;
698         }
699         ast_mutex_lock(&agentlock);
700         p = agents;
701         while(p) {
702                 p->dead = 1;
703                 p = p->next;
704         }
705         strcpy(moh, "default");
706         v = ast_variable_browse(cfg, "agents");
707         while(v) {
708                 /* Create the interface list */
709                 if (!strcasecmp(v->name, "agent")) {
710                         add_agent(v->value, 0);
711                 } else if (!strcasecmp(v->name, "group")) {
712                         group = ast_get_group(v->value);
713                 } else if (!strcasecmp(v->name, "autologoff")) {
714                         autologoff = atoi(v->value);
715                         if (autologoff < 0)
716                                 autologoff = 0;
717                 } else if (!strcasecmp(v->name, "ackcall")) {
718                         if (!strcasecmp(v->value, "always"))
719                                 ackcall = 2;
720                         else if (ast_true(v->value))
721                 ackcall = 1;
722                         else
723                                 ackcall = 0;
724                 } else if (!strcasecmp(v->name, "wrapuptime")) {
725                         wrapuptime = atoi(v->value);
726                         if (wrapuptime < 0)
727                                 wrapuptime = 0;
728                 } else if (!strcasecmp(v->name, "musiconhold")) {
729                         strncpy(moh, v->value, sizeof(moh) - 1);
730                 }
731                 v = v->next;
732         }
733         p = agents;
734         pl = NULL;
735         while(p) {
736                 pn = p->next;
737                 if (p->dead) {
738                         /* Unlink */
739                         if (pl)
740                                 pl->next = p->next;
741                         else
742                                 agents = p->next;
743                         /* Destroy if  appropriate */
744                         if (!p->owner) {
745                                 if (!p->chan) {
746                                         free(p);
747                                 } else {
748                                         /* Cause them to hang up */
749                                         ast_softhangup(p->chan, AST_SOFTHANGUP_EXPLICIT);
750                                 }
751                         }
752                 } else
753                         pl = p;
754                 p = pn;
755         }
756         ast_mutex_unlock(&agentlock);
757         ast_destroy(cfg);
758         return 0;
759 }
760
761 static int check_availability(struct agent_pvt *newlyavailable, int needlock)
762 {
763         struct ast_channel *chan=NULL, *parent=NULL;
764         struct agent_pvt *p;
765         int res;
766         ast_log(LOG_DEBUG, "Checking availability of '%s'\n", newlyavailable->agent);
767         if (needlock)
768                 ast_mutex_lock(&agentlock);
769         p = agents;
770         while(p) {
771                 if (p == newlyavailable) {
772                         p = p->next;
773                         continue;
774                 }
775                 ast_mutex_lock(&p->lock);
776                 if (!p->abouttograb && p->pending && ((p->group && (newlyavailable->group & p->group)) || !strcmp(p->agent, newlyavailable->agent))) {
777                         ast_log(LOG_DEBUG, "Call '%s' looks like a winner for agent '%s'\n", p->owner->name, newlyavailable->agent);
778                         /* We found a pending call, time to merge */
779                         chan = agent_new(newlyavailable, AST_STATE_DOWN);
780                         parent = p->owner;
781                         p->abouttograb = 1;
782                         ast_mutex_unlock(&p->lock);
783                         break;
784                 }
785                 ast_mutex_unlock(&p->lock);
786                 p = p->next;
787         }
788         if (needlock)
789                 ast_mutex_unlock(&agentlock);
790         if (parent && chan)  {
791                 if (newlyavailable->ackcall > 1) {
792                         /* Don't do beep here */
793                         res = 0;
794                 } else {
795                         ast_log( LOG_DEBUG, "Playing beep, lang '%s'\n", newlyavailable->chan->language);
796                         res = ast_streamfile(newlyavailable->chan, "beep", newlyavailable->chan->language);
797                         ast_log( LOG_DEBUG, "Played beep, result '%d'\n", res);
798                         if (!res) {
799                                 res = ast_waitstream(newlyavailable->chan, "");
800                                 ast_log( LOG_DEBUG, "Waited for stream, result '%d'\n", res);
801                         }
802                 }
803                 if (!res) {
804                         /* Note -- parent may have disappeared */
805                         if (p->abouttograb) {
806                                 newlyavailable->acknowledged = 1;
807                                 ast_setstate(parent, AST_STATE_UP);
808                                 ast_setstate(chan, AST_STATE_UP);
809                                 strncpy(parent->context, chan->context, sizeof(parent->context) - 1);
810                                 /* Go ahead and mark the channel as a zombie so that masquerade will
811                                    destroy it for us, and we need not call ast_hangup */
812                                 ast_mutex_lock(&parent->lock);
813                                 chan->zombie = 1;
814                                 ast_channel_masquerade(parent, chan);
815                                 ast_mutex_unlock(&parent->lock);
816                                 p->abouttograb = 0;
817                         } else {
818                                 ast_log(LOG_DEBUG, "Sneaky, parent disappeared in the mean time...\n");
819                                 agent_cleanup(newlyavailable);
820                         }
821                 } else {
822                         ast_log(LOG_DEBUG, "Ugh...  Agent hung up at exactly the wrong time\n");
823                         agent_cleanup(newlyavailable);
824                 }
825         }
826         return 0;
827 }
828
829 static int check_beep(struct agent_pvt *newlyavailable, int needlock)
830 {
831         struct agent_pvt *p;
832         int res=0;
833         ast_log(LOG_DEBUG, "Checking beep availability of '%s'\n", newlyavailable->agent);
834         if (needlock)
835                 ast_mutex_lock(&agentlock);
836         p = agents;
837         while(p) {
838                 if (p == newlyavailable) {
839                         p = p->next;
840                         continue;
841                 }
842                 ast_mutex_lock(&p->lock);
843                 if (!p->abouttograb && p->pending && ((p->group && (newlyavailable->group & p->group)) || !strcmp(p->agent, newlyavailable->agent))) {
844                         ast_log(LOG_DEBUG, "Call '%s' looks like a would-be winner for agent '%s'\n", p->owner->name, newlyavailable->agent);
845                         ast_mutex_unlock(&p->lock);
846                         break;
847                 }
848                 ast_mutex_unlock(&p->lock);
849                 p = p->next;
850         }
851         if (needlock)
852                 ast_mutex_unlock(&agentlock);
853         if (p) {
854                 ast_mutex_unlock(&newlyavailable->lock);
855                 ast_log( LOG_DEBUG, "Playing beep, lang '%s'\n", newlyavailable->chan->language);
856                 res = ast_streamfile(newlyavailable->chan, "beep", newlyavailable->chan->language);
857                 ast_log( LOG_DEBUG, "Played beep, result '%d'\n", res);
858                 if (!res) {
859                         res = ast_waitstream(newlyavailable->chan, "");
860                         ast_log( LOG_DEBUG, "Waited for stream, result '%d'\n", res);
861                 }
862                 ast_mutex_lock(&newlyavailable->lock);
863         }
864         return res;
865 }
866
867 static struct ast_channel *agent_request(char *type, int format, void *data)
868 {
869         struct agent_pvt *p;
870         struct ast_channel *chan = NULL;
871         char *s;
872         unsigned int groupmatch;
873         int waitforagent=0;
874         int hasagent = 0;
875         s = data;
876         if ((s[0] == '@') && (sscanf(s + 1, "%d", &groupmatch) == 1)) {
877                 groupmatch = (1 << groupmatch);
878         } else if ((s[0] == ':') && (sscanf(s + 1, "%d", &groupmatch) == 1)) {
879                 groupmatch = (1 << groupmatch);
880                 waitforagent = 1;
881         } else {
882                 groupmatch = 0;
883         }
884
885         /* Check actual logged in agents first */
886         ast_mutex_lock(&agentlock);
887         p = agents;
888         while(p) {
889                 ast_mutex_lock(&p->lock);
890                 if (!p->pending && ((groupmatch && (p->group & groupmatch)) || !strcmp(data, p->agent)) &&
891                                 !strlen(p->loginchan)) {
892                         if (p->chan)
893                                 hasagent++;
894                         if (!p->lastdisc.tv_sec) {
895                                 /* Agent must be registered, but not have any active call, and not be in a waiting state */
896                                 if (!p->owner && p->chan) {
897                                         /* Fixed agent */
898                                         chan = agent_new(p, AST_STATE_DOWN);
899                                 }
900                                 if (chan) {
901                                         ast_mutex_unlock(&p->lock);
902                                         break;
903                                 }
904                         }
905                 }
906                 ast_mutex_unlock(&p->lock);
907                 p = p->next;
908         }
909         if (!p) {
910                 p = agents;
911                 while(p) {
912                         ast_mutex_lock(&p->lock);
913                         if (!p->pending && ((groupmatch && (p->group & groupmatch)) || !strcmp(data, p->agent))) {
914                                 if (p->chan || strlen(p->loginchan))
915                                         hasagent++;
916                                 if (!p->lastdisc.tv_sec) {
917                                         /* Agent must be registered, but not have any active call, and not be in a waiting state */
918                                         if (!p->owner && p->chan) {
919                                                 /* Could still get a fixed agent */
920                                                 chan = agent_new(p, AST_STATE_DOWN);
921                                         } else if (!p->owner && strlen(p->loginchan)) {
922                                                 /* Adjustable agent */
923                                                 p->chan = ast_request("Local", format, p->loginchan);
924                                                 if (p->chan)
925                                                         chan = agent_new(p, AST_STATE_DOWN);
926                                         }
927                                         if (chan) {
928                                                 ast_mutex_unlock(&p->lock);
929                                                 break;
930                                         }
931                                 }
932                         }
933                         ast_mutex_unlock(&p->lock);
934                         p = p->next;
935                 }
936         }
937
938         if (!chan && waitforagent) {
939                 /* No agent available -- but we're requesting to wait for one.
940                    Allocate a place holder */
941                 if (hasagent) {
942                         ast_log(LOG_DEBUG, "Creating place holder for '%s'\n", s);
943                         p = add_agent(data, 1);
944                         p->group = groupmatch;
945                         chan = agent_new(p, AST_STATE_DOWN);
946                         if (!chan) {
947                                 ast_log(LOG_WARNING, "Weird...  Fix this to drop the unused pending agent\n");
948                         }
949                 } else
950                         ast_log(LOG_DEBUG, "Not creating place holder for '%s' since nobody logged in\n", s);
951         }
952         ast_mutex_unlock(&agentlock);
953         return chan;
954 }
955
956 static int powerof(unsigned int v)
957 {
958         int x;
959         for (x=0;x<32;x++) {
960                 if (v & (1 << x)) return x;
961         }
962         return 0;
963 }
964
965 static int agents_show(int fd, int argc, char **argv)
966 {
967         struct agent_pvt *p;
968         char username[256];
969         char location[256];
970         char talkingto[256];
971         char moh[256];
972
973         if (argc != 2)
974                 return RESULT_SHOWUSAGE;
975         ast_mutex_lock(&agentlock);
976         p = agents;
977         while(p) {
978                 ast_mutex_lock(&p->lock);
979                 if (p->pending) {
980                         if (p->group)
981                                 ast_cli(fd, "-- Pending call to group %d\n", powerof(p->group));
982                         else
983                                 ast_cli(fd, "-- Pending call to agent %s\n", p->agent);
984                 } else {
985                         if (strlen(p->name))
986                                 snprintf(username, sizeof(username), "(%s) ", p->name);
987                         else
988                                 strcpy(username, "");
989                         if (p->chan) {
990                                 snprintf(location, sizeof(location), "logged in on %s", p->chan->name);
991                                 if (p->owner && p->owner->bridge) {
992                                         snprintf(talkingto, sizeof(talkingto), " talking to %s", p->owner->bridge->name);
993                                 } else {
994                                         strcpy(talkingto, " is idle");
995                                 }
996                         } else if (strlen(p->loginchan)) {
997                                 snprintf(location, sizeof(location) - 20, "available at '%s'", p->loginchan);
998                                 strcpy(talkingto, "");
999                                 if (p->acknowledged)
1000                                         strcat(location, " (Confirmed)");
1001                         } else {
1002                                 strcpy(location, "not logged in");
1003                                 strcpy(talkingto, "");
1004                         }
1005                         if (strlen(p->moh))
1006                                 snprintf(moh, sizeof(moh), " (musiconhold is '%s')", p->moh);
1007                         ast_cli(fd, "%-12.12s %s%s%s%s\n", p->agent, 
1008                                         username, location, talkingto, moh);
1009                 }
1010                 ast_mutex_unlock(&p->lock);
1011                 p = p->next;
1012         }
1013         ast_mutex_unlock(&agentlock);
1014         return RESULT_SUCCESS;
1015 }
1016
1017 static char show_agents_usage[] = 
1018 "Usage: show agents\n"
1019 "       Provides summary information on agents.\n";
1020
1021 static struct ast_cli_entry cli_show_agents = {
1022         { "show", "agents", NULL }, agents_show, 
1023         "Show status of agents", show_agents_usage, NULL };
1024
1025 STANDARD_LOCAL_USER;
1026 LOCAL_USER_DECL;
1027
1028 static int __login_exec(struct ast_channel *chan, void *data, int callbackmode)
1029 {
1030         int res=0;
1031         int tries = 0;
1032         struct agent_pvt *p;
1033         struct localuser *u;
1034         struct timeval tv;
1035         char user[AST_MAX_AGENT];
1036         char pass[AST_MAX_AGENT];
1037         char xpass[AST_MAX_AGENT] = "";
1038         char *errmsg;
1039         char info[512];
1040         char *opt_user = NULL;
1041         char *options = NULL;
1042         char *context = NULL;
1043         char *exten = NULL;
1044         int play_announcement;
1045         char *filename = "agent-loginok";
1046         
1047         LOCAL_USER_ADD(u);
1048
1049         /* Parse the arguments XXX Check for failure XXX */
1050         strncpy(info, (char *)data, strlen((char *)data) + AST_MAX_EXTENSION-1);
1051         opt_user = info;
1052         if( opt_user ) {
1053                 options = strchr(opt_user, '|');
1054                 if (options) {
1055                         *options = '\0';
1056                         options++;
1057                         if (callbackmode) {
1058                                 context = strchr(options, '@');
1059                                 if (context) {
1060                                         *context = '\0';
1061                                         context++;
1062                                 }
1063                                 exten = options;
1064                                 while(*exten && ((*exten < '0') || (*exten > '9'))) exten++;
1065                                 if (!*exten)
1066                                         exten = NULL;
1067                         }
1068                 }
1069         }
1070
1071         if (chan->_state != AST_STATE_UP)
1072                 res = ast_answer(chan);
1073         if (!res) {
1074                 if( opt_user && strlen(opt_user))
1075                         strncpy( user, opt_user, AST_MAX_AGENT );
1076                 else
1077                         res = ast_app_getdata(chan, "agent-user", user, sizeof(user) - 1, 0);
1078         }
1079         while (!res && (tries < 3)) {
1080                 /* Check for password */
1081                 ast_mutex_lock(&agentlock);
1082                 p = agents;
1083                 while(p) {
1084                         if (!strcmp(p->agent, user) && !p->pending)
1085                                 strncpy(xpass, p->password, sizeof(xpass) - 1);
1086                         p = p->next;
1087                 }
1088                 ast_mutex_unlock(&agentlock);
1089                 if (!res) {
1090                         if (strlen(xpass))
1091                                 res = ast_app_getdata(chan, "agent-pass", pass, sizeof(pass) - 1, 0);
1092                         else
1093                                 strcpy(pass, "");
1094                 }
1095                 errmsg = "agent-incorrect";
1096
1097 #if 0
1098                 ast_log(LOG_NOTICE, "user: %s, pass: %s\n", user, pass);
1099 #endif          
1100
1101                 /* Check again for accuracy */
1102                 ast_mutex_lock(&agentlock);
1103                 p = agents;
1104                 while(p) {
1105                         ast_mutex_lock(&p->lock);
1106                         if (!strcmp(p->agent, user) &&
1107                                 !strcmp(p->password, pass) && !p->pending) {
1108                                         if (!p->chan) {
1109                                                 if (callbackmode) {
1110                                                         char tmpchan[256] = "";
1111                                                         int pos = 0;
1112                                                         /* Retrieve login chan */
1113                                                         for (;;) {
1114                                                                 if (exten) {
1115                                                                         strncpy(tmpchan, exten, sizeof(tmpchan) - 1);
1116                                                                         res = 0;
1117                                                                 } else
1118                                                                         res = ast_app_getdata(chan, "agent-newlocation", tmpchan+pos, sizeof(tmpchan) - 2, 0);
1119                                                                 if (!strlen(tmpchan) || ast_exists_extension(chan, context && strlen(context) ? context : "default", tmpchan,
1120                                                                                         1, NULL))
1121                                                                         break;
1122                                                                 if (exten) {
1123                                                                         ast_log(LOG_WARNING, "Extension '%s' is not valid for automatic login of agent '%s'\n", exten, p->agent);
1124                                                                         exten = NULL;
1125                                                                         pos = 0;
1126                                                                 } else {
1127                                                                         res = ast_streamfile(chan, "invalid", chan->language);
1128                                                                         if (!res)
1129                                                                                 res = ast_waitstream(chan, AST_DIGIT_ANY);
1130                                                                         if (res > 0) {
1131                                                                                 tmpchan[0] = res;
1132                                                                                 tmpchan[1] = '\0';
1133                                                                                 pos = 1;
1134                                                                         } else {
1135                                                                                 tmpchan[0] = '\0';
1136                                                                                 pos = 0;
1137                                                                         }
1138                                                                 }
1139                                                         }
1140                                                         if (!res) {
1141                                                                 if (context && strlen(context) && strlen(tmpchan))
1142                                                                         snprintf(p->loginchan, sizeof(p->loginchan), "%s@%s", tmpchan, context);
1143                                                                 else
1144                                                                         strncpy(p->loginchan, tmpchan, sizeof(p->loginchan) - 1);
1145                                                                 if (!strlen(p->loginchan))
1146                                                                         filename = "agent-loggedoff";
1147                                                                 p->acknowledged = 0;
1148                                                         }
1149                                                 } else {
1150                                                         strcpy(p->loginchan, "");
1151                                                         p->acknowledged = 0;
1152                                                 }
1153                                                 play_announcement = 1;
1154                                                 if( options )
1155                                                         if( strchr( options, 's' ) )
1156                                                                 play_announcement = 0;
1157                                                 if( !res && play_announcement )
1158                                                         res = ast_streamfile(chan, filename, chan->language);
1159                                                 if (!res)
1160                                                         ast_waitstream(chan, "");
1161                                                 if (!res) {
1162                                                         res = ast_set_read_format(chan, ast_best_codec(chan->nativeformats));
1163                                                         if (res)
1164                                                                 ast_log(LOG_WARNING, "Unable to set read format to %d\n", ast_best_codec(chan->nativeformats));
1165                                                 }
1166                                                 if (!res) {
1167                                                         ast_set_write_format(chan, ast_best_codec(chan->nativeformats));
1168                                                         if (res)
1169                                                                 ast_log(LOG_WARNING, "Unable to set write format to %d\n", ast_best_codec(chan->nativeformats));
1170                                                 }
1171                                                 /* Check once more just in case */
1172                                                 if (p->chan)
1173                                                         res = -1;
1174                                                 if (callbackmode && !res) {
1175                                                         /* Just say goodbye and be done with it */
1176                                                         if (!res)
1177                                                                 res = ast_safe_sleep(chan, 500);
1178                                                         res = ast_streamfile(chan, "vm-goodbye", chan->language);
1179                                                         if (!res)
1180                                                                 res = ast_waitstream(chan, "");
1181                                                         if (!res)
1182                                                                 res = ast_safe_sleep(chan, 1000);
1183                                                         ast_mutex_unlock(&p->lock);
1184                                                         ast_mutex_unlock(&agentlock);
1185                                                 } else if (!res) {
1186 #ifdef HONOR_MUSIC_CLASS
1187                                                         /* check if the moh class was changed with setmusiconhold */
1188                                                         if (*(chan->musicclass))
1189                                                                 strncpy(p->moh, chan->musicclass, sizeof(p->moh) - 1);
1190 #endif                                                          
1191                                                         ast_moh_start(chan, p->moh);
1192                                                         manager_event(EVENT_FLAG_AGENT, "Agentlogin",
1193                                                                 "Agent: %s\r\n"
1194                                                                 "Channel: %s\r\n",
1195                                                                 p->agent, chan->name);
1196                                                         if (option_verbose > 2)
1197                                                                 ast_verbose(VERBOSE_PREFIX_3 "Agent '%s' logged in (format %s/%s)\n", p->agent,
1198                                                                                                 ast_getformatname(chan->readformat), ast_getformatname(chan->writeformat));
1199                                                         /* Login this channel and wait for it to
1200                                                            go away */
1201                                                         p->chan = chan;
1202                                                         if (p->ackcall > 1)
1203                                                                 check_beep(p, 0);
1204                                                         else
1205                                                                 check_availability(p, 0);
1206                                                         ast_mutex_unlock(&p->lock);
1207                                                         ast_mutex_unlock(&agentlock);
1208                                                         while (res >= 0) {
1209                                                                 ast_mutex_lock(&p->lock);
1210                                                                 if (p->chan != chan)
1211                                                                         res = -1;
1212                                                                 ast_mutex_unlock(&p->lock);
1213                                                                 /* Yield here so other interested threads can kick in. */
1214                                                                 sched_yield();
1215                                                                 if (res)
1216                                                                         break;
1217
1218                                                                 ast_mutex_lock(&agentlock);
1219                                                                 ast_mutex_lock(&p->lock);
1220                                                                 if (p->lastdisc.tv_sec) {
1221                                                                         gettimeofday(&tv, NULL);
1222                                                                         if ((tv.tv_sec - p->lastdisc.tv_sec) * 1000 + 
1223                                                                                 (tv.tv_usec - p->lastdisc.tv_usec) / 1000 > p->wrapuptime) {
1224                                                                                         ast_log(LOG_DEBUG, "Wrapup time expired!\n");
1225                                                                                 memset(&p->lastdisc, 0, sizeof(p->lastdisc));
1226                                                                                 if (p->ackcall > 1)
1227                                                                                         check_beep(p, 0);
1228                                                                                 else
1229                                                                                         check_availability(p, 0);
1230                                                                         }
1231                                                                 }
1232                                                                 ast_mutex_unlock(&p->lock);
1233                                                                 ast_mutex_unlock(&agentlock);
1234                                                                 /*      Synchronize channel ownership between call to agent and itself. */
1235                                                                 ast_mutex_lock( &p->app_lock );
1236                                                                 ast_mutex_lock(&p->lock);
1237                                                                 p->owning_app = pthread_self();
1238                                                                 ast_mutex_unlock(&p->lock);
1239                                                                 if (p->ackcall > 1) 
1240                                                                         res = agent_ack_sleep(p);
1241                                                                 else
1242                                                                         res = ast_safe_sleep_conditional( chan, 1000,
1243                                                                                                         agent_cont_sleep, p );
1244                                                                 ast_mutex_unlock( &p->app_lock );
1245                                                                 if ((p->ackcall > 1)  && (res == 1)) {
1246                                                                         ast_mutex_lock(&agentlock);
1247                                                                         ast_mutex_lock(&p->lock);
1248                                                                         check_availability(p, 0);
1249                                                                         ast_mutex_unlock(&p->lock);
1250                                                                         ast_mutex_unlock(&agentlock);
1251                                                                         res = 0;
1252                                                                 }
1253                                                                 sched_yield();
1254                                                         }
1255                                                         ast_mutex_lock(&p->lock);
1256                                                         if (res && p->owner) 
1257                                                                 ast_log(LOG_WARNING, "Huh?  We broke out when there was still an owner?\n");
1258                                                         /* Log us off if appropriate */
1259                                                         if (p->chan == chan)
1260                                                                 p->chan = NULL;
1261                                                         p->acknowledged = 0;
1262                                                         ast_mutex_unlock(&p->lock);
1263                                                         if (option_verbose > 2)
1264                                                                 ast_verbose(VERBOSE_PREFIX_3 "Agent '%s' logged out\n", p->agent);
1265                                                         manager_event(EVENT_FLAG_AGENT, "Agentlogoff",
1266                                                                 "Agent: %s\r\n",
1267                                                                 p->agent);
1268                                                         /* If there is no owner, go ahead and kill it now */
1269                                                         if (p->dead && !p->owner)
1270                                                                 free(p);
1271                                                 }
1272                                                 else {
1273                                                         ast_mutex_unlock(&p->lock);
1274                                                         p = NULL;
1275                                                 }
1276                                                 res = -1;
1277                                         } else {
1278                                                 ast_mutex_unlock(&p->lock);
1279                                                 errmsg = "agent-alreadyon";
1280                                                 p = NULL;
1281                                         }
1282                                         break;
1283                         }
1284                         ast_mutex_unlock(&p->lock);
1285                         p = p->next;
1286                 }
1287                 if (!p)
1288                         ast_mutex_unlock(&agentlock);
1289
1290                 if (!res)
1291                         res = ast_app_getdata(chan, errmsg, user, sizeof(user) - 1, 0);
1292         }
1293                 
1294         LOCAL_USER_REMOVE(u);
1295         /* Always hangup */
1296         return -1;
1297 }
1298
1299 static int login_exec(struct ast_channel *chan, void *data)
1300 {
1301         return __login_exec(chan, data, 0);
1302 }
1303
1304 static int callback_exec(struct ast_channel *chan, void *data)
1305 {
1306         return __login_exec(chan, data, 1);
1307 }
1308
1309 int load_module()
1310 {
1311         /* Make sure we can register our sip channel type */
1312         if (ast_channel_register(type, tdesc, capability, agent_request)) {
1313                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1314                 return -1;
1315         }
1316         ast_register_application(app, login_exec, synopsis, descrip);
1317         ast_register_application(app2, callback_exec, synopsis2, descrip2);
1318         ast_cli_register(&cli_show_agents);
1319         /* Read in the config */
1320         read_agent_config();
1321         return 0;
1322 }
1323
1324 int reload()
1325 {
1326         read_agent_config();
1327         return 0;
1328 }
1329
1330 int unload_module()
1331 {
1332         struct agent_pvt *p;
1333         /* First, take us out of the channel loop */
1334         ast_cli_unregister(&cli_show_agents);
1335         ast_unregister_application(app);
1336         ast_unregister_application(app2);
1337         ast_channel_unregister(type);
1338         if (!ast_mutex_lock(&agentlock)) {
1339                 /* Hangup all interfaces if they have an owner */
1340                 p = agents;
1341                 while(p) {
1342                         if (p->owner)
1343                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1344                         p = p->next;
1345                 }
1346                 agents = NULL;
1347                 ast_mutex_unlock(&agentlock);
1348         } else {
1349                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1350                 return -1;
1351         }               
1352         return 0;
1353 }
1354
1355 int usecount()
1356 {
1357         int res;
1358         ast_mutex_lock(&usecnt_lock);
1359         res = usecnt;
1360         ast_mutex_unlock(&usecnt_lock);
1361         return res;
1362 }
1363
1364 char *key()
1365 {
1366         return ASTERISK_GPL_KEY;
1367 }
1368
1369 char *description()
1370 {
1371         return desc;
1372 }
1373