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