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