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