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