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