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