Fix potential race in check_availability
[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                                 chan->zombie = 1;
638                                 ast_channel_masquerade(parent, chan);
639                                 p->abouttograb = 0;
640                         } else {
641                                 ast_log(LOG_DEBUG, "Sneaky, parent disappeared in the mean time...\n");
642                                 agent_cleanup(newlyavailable);
643                         }
644                 } else {
645                         ast_log(LOG_DEBUG, "Ugh...  Agent hung up at exactly the wrong time\n");
646                         agent_cleanup(newlyavailable);
647                 }
648         }
649         return 0;
650 }
651
652 static struct ast_channel *agent_request(char *type, int format, void *data)
653 {
654         struct agent_pvt *p;
655         struct ast_channel *chan = NULL;
656         char *s;
657         unsigned int groupmatch;
658         int waitforagent=0;
659         s = data;
660         if ((s[0] == '@') && (sscanf(s + 1, "%d", &groupmatch) == 1)) {
661                 groupmatch = (1 << groupmatch);
662         } else if ((s[0] == ':') && (sscanf(s + 1, "%d", &groupmatch) == 1)) {
663                 groupmatch = (1 << groupmatch);
664                 waitforagent = 1;
665         } else {
666                 groupmatch = 0;
667         }
668         ast_pthread_mutex_lock(&agentlock);
669         p = agents;
670         while(p) {
671                 ast_pthread_mutex_lock(&p->lock);
672                 if (!p->pending && ((groupmatch && (p->group & groupmatch)) || !strcmp(data, p->agent))) {
673                         /* Agent must be registered, but not have any active call */
674                         if (!p->owner && p->chan) {
675                                 /* Fixed agent */
676                                 chan = agent_new(p, AST_STATE_DOWN);
677                         } else if (!p->owner && strlen(p->loginchan)) {
678                                 /* Adjustable agent */
679                                 p->chan = ast_request("Local", format, p->loginchan);
680                                 if (p->chan)
681                                         chan = agent_new(p, AST_STATE_DOWN);
682                         }
683                         if (chan) {
684                                 ast_pthread_mutex_unlock(&p->lock);
685                                 break;
686                         }
687                 }
688                 ast_pthread_mutex_unlock(&p->lock);
689                 p = p->next;
690         }
691         if (!chan && waitforagent) {
692                 /* No agent available -- but we're requesting to wait for one.
693                    Allocate a place holder */
694                 ast_log(LOG_DEBUG, "Creating place holder for '%s'\n", s);
695                 p = add_agent(data, 1);
696                 p->group = groupmatch;
697                 chan = agent_new(p, AST_STATE_DOWN);
698                 if (!chan) {
699                         ast_log(LOG_WARNING, "Weird...  Fix this to drop the unused pending agent\n");
700                 }
701         }
702         ast_pthread_mutex_unlock(&agentlock);
703         return chan;
704 }
705
706 static int powerof(unsigned int v)
707 {
708         int x;
709         for (x=0;x<32;x++) {
710                 if (v & (1 << x)) return x;
711         }
712         return 0;
713 }
714
715 static int agents_show(int fd, int argc, char **argv)
716 {
717         struct agent_pvt *p;
718         char username[256];
719         char location[256];
720         char talkingto[256];
721         char moh[256];
722
723         if (argc != 2)
724                 return RESULT_SHOWUSAGE;
725         ast_pthread_mutex_lock(&agentlock);
726         p = agents;
727         while(p) {
728                 ast_pthread_mutex_lock(&p->lock);
729                 if (p->pending) {
730                         if (p->group)
731                                 ast_cli(fd, "-- Pending call to group %d\n", powerof(p->group));
732                         else
733                                 ast_cli(fd, "-- Pending call to agent %s\n", p->agent);
734                 } else {
735                         if (strlen(p->name))
736                                 snprintf(username, sizeof(username), "(%s) ", p->name);
737                         else
738                                 strcpy(username, "");
739                         if (p->chan) {
740                                 snprintf(location, sizeof(location), "logged in on %s", p->chan->name);
741                                 if (p->owner && p->owner->bridge) {
742                                         snprintf(talkingto, sizeof(talkingto), " talking to %s", p->owner->bridge->name);
743                                 } else {
744                                         strcpy(talkingto, " is idle");
745                                 }
746                         } else if (strlen(p->loginchan)) {
747                                 snprintf(location, sizeof(location) - 20, "available at '%s'", p->loginchan);
748                                 strcpy(talkingto, "");
749                                 if (p->acknowledged)
750                                         strcat(location, " (Confirmed)");
751                         } else {
752                                 strcpy(location, "not logged in");
753                                 strcpy(talkingto, "");
754                         }
755                         if (strlen(p->moh))
756                                 snprintf(moh, sizeof(moh), "(musiconhold is '%s')", p->moh);
757                         ast_cli(fd, "%-12.12s %s%s%s%s\n", p->agent, 
758                                         username, location, talkingto, moh);
759                 }
760                 ast_pthread_mutex_unlock(&p->lock);
761                 p = p->next;
762         }
763         ast_pthread_mutex_unlock(&agentlock);
764         return RESULT_SUCCESS;
765 }
766
767 static char show_agents_usage[] = 
768 "Usage: show agents\n"
769 "       Provides summary information on agents.\n";
770
771 static struct ast_cli_entry cli_show_agents = {
772         { "show", "agents", NULL }, agents_show, 
773         "Show status of agents", show_agents_usage, NULL };
774
775 STANDARD_LOCAL_USER;
776 LOCAL_USER_DECL;
777
778 static int __login_exec(struct ast_channel *chan, void *data, int callbackmode)
779 {
780         int res=0;
781         int tries = 0;
782         struct agent_pvt *p;
783         struct localuser *u;
784         char user[AST_MAX_AGENT];
785         char pass[AST_MAX_AGENT];
786         char xpass[AST_MAX_AGENT] = "";
787         char *errmsg;
788         char info[512];
789         char *opt_user = NULL;
790         char *options = NULL;
791         int play_announcement;
792         char *filename = "agent-loginok";
793         
794         LOCAL_USER_ADD(u);
795
796         /* Parse the arguments XXX Check for failure XXX */
797         strncpy(info, (char *)data, strlen((char *)data) + AST_MAX_EXTENSION-1);
798         opt_user = info;
799         if( opt_user ) {
800                 options = strchr(opt_user, '|');
801                 if (options) {
802                         *options = '\0';
803                         options++;
804                 }
805         }
806
807         if (chan->_state != AST_STATE_UP)
808                 res = ast_answer(chan);
809         if (!res) {
810                 if( opt_user && strlen(opt_user))
811                         strncpy( user, opt_user, AST_MAX_AGENT );
812                 else
813                         res = ast_app_getdata(chan, "agent-user", user, sizeof(user) - 1, 0);
814         }
815         while (!res && (tries < 3)) {
816                 /* Check for password */
817                 ast_pthread_mutex_lock(&agentlock);
818                 p = agents;
819                 while(p) {
820                         if (!strcmp(p->agent, user) && !p->pending)
821                                 strncpy(xpass, p->password, sizeof(xpass) - 1);
822                         p = p->next;
823                 }
824                 ast_pthread_mutex_unlock(&agentlock);
825                 if (!res) {
826                         if (strlen(xpass))
827                                 res = ast_app_getdata(chan, "agent-pass", pass, sizeof(pass) - 1, 0);
828                         else
829                                 strcpy(pass, "");
830                 }
831                 errmsg = "agent-incorrect";
832
833 #if 0
834                 ast_log(LOG_NOTICE, "user: %s, pass: %s\n", user, pass);
835 #endif          
836
837                 /* Check again for accuracy */
838                 ast_pthread_mutex_lock(&agentlock);
839                 p = agents;
840                 while(p) {
841                         ast_pthread_mutex_lock(&p->lock);
842                         if (!strcmp(p->agent, user) &&
843                                 !strcmp(p->password, pass) && !p->pending) {
844                                         if (!p->chan) {
845                                                 if (callbackmode) {
846                                                         char tmpchan[256] = "";
847                                                         /* Retrieve login chan */
848                                                         res = ast_app_getdata(chan, "agent-newlocation", tmpchan, sizeof(tmpchan) - 1, 0);
849                                                         if (!res) {
850                                                                 strncpy(p->loginchan, tmpchan, sizeof(p->loginchan) - 1);
851                                                                 if (!strlen(p->loginchan))
852                                                                         filename = "agent-loggedoff";
853                                                                 p->acknowledged = 0;
854                                                         }
855                                                 } else {
856                                                         strcpy(p->loginchan, "");
857                                                         p->acknowledged = 0;
858                                                 }
859                                                 play_announcement = 1;
860                                                 if( options )
861                                                         if( strchr( options, 's' ) )
862                                                                 play_announcement = 0;
863                                                 if( play_announcement )
864                                                         res = ast_streamfile(chan, filename, chan->language);
865                                                 if (!res)
866                                                         ast_waitstream(chan, "");
867                                                 if (!res) {
868                                                         res = ast_set_read_format(chan, ast_best_codec(chan->nativeformats));
869                                                         if (res)
870                                                                 ast_log(LOG_WARNING, "Unable to set read format to %d\n", ast_best_codec(chan->nativeformats));
871                                                 }
872                                                 if (!res) {
873                                                         ast_set_write_format(chan, ast_best_codec(chan->nativeformats));
874                                                         if (res)
875                                                                 ast_log(LOG_WARNING, "Unable to set write format to %d\n", ast_best_codec(chan->nativeformats));
876                                                 }
877                                                 /* Check once more just in case */
878                                                 if (p->chan)
879                                                         res = -1;
880                                                 if (callbackmode && !res) {
881                                                         /* Just say goodbye and be done with it */
882                                                         if (!res)
883                                                                 res = ast_safe_sleep(chan, 500);
884                                                         res = ast_streamfile(chan, "vm-goodbye", chan->language);
885                                                         if (!res)
886                                                                 res = ast_waitstream(chan, "");
887                                                         if (!res)
888                                                                 res = ast_safe_sleep(chan, 1000);
889                                                         ast_pthread_mutex_unlock(&p->lock);
890                                                         ast_pthread_mutex_unlock(&agentlock);
891                                                 } else if (!res) {
892                                                         /* check if the moh class was changed with setmusiconhold */
893                                                         if (*(chan->musicclass))
894                                                                 strncpy(p->moh, chan->musicclass, sizeof(p->moh) - 1);
895                                                         ast_moh_start(chan, p->moh);
896                                                         manager_event(EVENT_FLAG_AGENT, "Agentlogin",
897                                                                 "Agent: %s\r\n"
898                                                                 "Channel: %s\r\n",
899                                                                 p->agent, chan->name);
900                                                         if (option_verbose > 2)
901                                                                 ast_verbose(VERBOSE_PREFIX_3 "Agent '%s' logged in (format %d/%d)\n", p->agent,
902                                                                                                 chan->readformat, chan->writeformat);
903                                                         /* Login this channel and wait for it to
904                                                            go away */
905                                                         p->chan = chan;
906                                                         p->acknowledged = 1;
907                                                         check_availability(p, 0);
908                                                         ast_pthread_mutex_unlock(&p->lock);
909                                                         ast_pthread_mutex_unlock(&agentlock);
910                                                         while (res >= 0) {
911                                                                 ast_pthread_mutex_lock(&p->lock);
912                                                                 if (p->chan != chan)
913                                                                         res = -1;
914                                                                 ast_pthread_mutex_unlock(&p->lock);
915                                                                 /* Yield here so other interested threads can kick in. */
916                                                                 sched_yield();
917                                                                 if (res)
918                                                                         break;
919
920                                                                 /*      Synchronize channel ownership between call to agent and itself. */
921                                                                 pthread_mutex_lock( &p->app_lock );
922                                                                 ast_pthread_mutex_lock(&p->lock);
923                                                                 p->owning_app = pthread_self();
924                                                                 ast_pthread_mutex_unlock(&p->lock);
925                                                                 res = ast_safe_sleep_conditional( chan, 1000,
926                                                                                                                 agent_cont_sleep, p );
927                                                                 pthread_mutex_unlock( &p->app_lock );
928                                                                 sched_yield();
929                                                         }
930                                                         ast_pthread_mutex_lock(&p->lock);
931                                                         if (res && p->owner) 
932                                                                 ast_log(LOG_WARNING, "Huh?  We broke out when there was still an owner?\n");
933                                                         /* Log us off if appropriate */
934                                                         if (p->chan == chan)
935                                                                 p->chan = NULL;
936                                                         p->acknowledged = 0;
937                                                         ast_pthread_mutex_unlock(&p->lock);
938                                                         if (option_verbose > 2)
939                                                                 ast_verbose(VERBOSE_PREFIX_3 "Agent '%s' logged out\n", p->agent);
940                                                         manager_event(EVENT_FLAG_AGENT, "Agentlogoff",
941                                                                 "Agent: %s\r\n",
942                                                                 p->agent);
943                                                         /* If there is no owner, go ahead and kill it now */
944                                                         if (p->dead && !p->owner)
945                                                                 free(p);
946                                                 }
947                                                 else {
948                                                         ast_pthread_mutex_unlock(&p->lock);
949                                                         p = NULL;
950                                                 }
951                                                 res = -1;
952                                         } else {
953                                                 ast_pthread_mutex_unlock(&p->lock);
954                                                 errmsg = "agent-alreadyon";
955                                                 p = NULL;
956                                         }
957                                         break;
958                         }
959                         ast_pthread_mutex_unlock(&p->lock);
960                         p = p->next;
961                 }
962                 if (!p)
963                         ast_pthread_mutex_unlock(&agentlock);
964
965                 if (!res)
966                         res = ast_app_getdata(chan, errmsg, user, sizeof(user) - 1, 0);
967         }
968                 
969         LOCAL_USER_REMOVE(u);
970         /* Always hangup */
971         return -1;
972 }
973
974 static int login_exec(struct ast_channel *chan, void *data)
975 {
976         return __login_exec(chan, data, 0);
977 }
978
979 static int callback_exec(struct ast_channel *chan, void *data)
980 {
981         return __login_exec(chan, data, 1);
982 }
983
984 int load_module()
985 {
986         /* Make sure we can register our sip channel type */
987         if (ast_channel_register(type, tdesc, capability, agent_request)) {
988                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
989                 return -1;
990         }
991         ast_register_application(app, login_exec, synopsis, descrip);
992         ast_register_application(app2, callback_exec, synopsis2, descrip2);
993         ast_cli_register(&cli_show_agents);
994         /* Read in the config */
995         read_agent_config();
996         return 0;
997 }
998
999 int reload()
1000 {
1001         read_agent_config();
1002         return 0;
1003 }
1004
1005 int unload_module()
1006 {
1007         struct agent_pvt *p;
1008         /* First, take us out of the channel loop */
1009         ast_cli_unregister(&cli_show_agents);
1010         ast_unregister_application(app);
1011         ast_unregister_application(app2);
1012         ast_channel_unregister(type);
1013         if (!ast_pthread_mutex_lock(&agentlock)) {
1014                 /* Hangup all interfaces if they have an owner */
1015                 p = agents;
1016                 while(p) {
1017                         if (p->owner)
1018                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1019                         p = p->next;
1020                 }
1021                 agents = NULL;
1022                 ast_pthread_mutex_unlock(&agentlock);
1023         } else {
1024                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1025                 return -1;
1026         }               
1027         return 0;
1028 }
1029
1030 int usecount()
1031 {
1032         int res;
1033         ast_pthread_mutex_lock(&usecnt_lock);
1034         res = usecnt;
1035         ast_pthread_mutex_unlock(&usecnt_lock);
1036         return res;
1037 }
1038
1039 char *key()
1040 {
1041         return ASTERISK_GPL_KEY;
1042 }
1043
1044 char *description()
1045 {
1046         return desc;
1047 }
1048