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