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