Clear acknowledged flag on hangup
[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                         p->acknowledged = 0;
394                         if (p->chan) {
395                                 /* Recognize the hangup and pass it along immediately */
396                                 ast_hangup(p->chan);
397                                 p->chan = NULL;
398                         }
399                         ast_log(LOG_DEBUG, "Hungup, howlong is %d, autologoff is %d\n", howlong, p->autologoff);
400                         if (howlong  && p->autologoff && (howlong > p->autologoff)) {
401                                 ast_log(LOG_NOTICE, "Agent '%s' didn't answer/confirm within %d seconds (waited %d)\n", p->name, p->autologoff, howlong);
402                                 strcpy(p->loginchan, "");
403                         }
404                 } else if (p->dead) {
405                         ast_pthread_mutex_lock(&p->chan->lock);
406                         ast_softhangup(p->chan, AST_SOFTHANGUP_EXPLICIT);
407                         ast_pthread_mutex_unlock(&p->chan->lock);
408                 } else {
409                         ast_pthread_mutex_lock(&p->chan->lock);
410                         ast_moh_start(p->chan, p->moh);
411                         ast_pthread_mutex_unlock(&p->chan->lock);
412                 }
413         }
414 #if 0
415                 ast_pthread_mutex_unlock(&p->lock);
416                 /* Release ownership of the agent to other threads (presumably running the login app). */
417                 ast_pthread_mutex_unlock(&p->app_lock);
418         } else if (p->dead) {
419                 /* Go ahead and lose it */
420                 ast_pthread_mutex_unlock(&p->lock);
421                 /* Release ownership of the agent to other threads (presumably running the login app). */
422                 ast_pthread_mutex_unlock(&p->app_lock);
423         } else {
424                 ast_pthread_mutex_unlock(&p->lock);
425                 /* Release ownership of the agent to other threads (presumably running the login app). */
426                 ast_pthread_mutex_unlock(&p->app_lock);
427         }
428 #endif  
429         ast_pthread_mutex_unlock(&p->lock);
430         /* Release ownership of the agent to other threads (presumably running the login app). */
431         ast_pthread_mutex_unlock(&p->app_lock);
432
433         if (p->pending) {
434                 ast_pthread_mutex_lock(&agentlock);
435                 agent_unlink(p);
436                 ast_pthread_mutex_unlock(&agentlock);
437         }
438         if (p->abouttograb) {
439                 /* Let the "about to grab" thread know this isn't valid anymore, and let it
440                    kill it later */
441                 p->abouttograb = 0;
442         } else if (p->dead) {
443                 free(p);
444         } else if (p->chan) {
445                 /* Not dead -- check availability now */
446                 ast_pthread_mutex_lock(&p->lock);
447                 /* check_availability(p, 1); */
448                 /* Store last disconnect time */
449                 gettimeofday(&p->lastdisc, NULL);
450                 ast_pthread_mutex_unlock(&p->lock);
451         }
452         return 0;
453 }
454
455 static int agent_cont_sleep( void *data )
456 {
457         struct agent_pvt *p;
458         struct timeval tv;
459         int res;
460
461         p = (struct agent_pvt *)data;
462
463         ast_pthread_mutex_lock(&p->lock);
464         res = p->app_sleep_cond;
465         if (p->lastdisc.tv_sec) {
466                 gettimeofday(&tv, NULL);
467                 if ((tv.tv_sec - p->lastdisc.tv_sec) * 1000 + 
468                         (tv.tv_usec - p->lastdisc.tv_usec) / 1000 > p->wrapuptime) 
469                         res = 1;
470         }
471         ast_pthread_mutex_unlock(&p->lock);
472 #if 0
473         if( !res )
474                 ast_log( LOG_DEBUG, "agent_cont_sleep() returning %d\n", res );
475 #endif          
476         return res;
477 }
478
479 static struct ast_channel *agent_new(struct agent_pvt *p, int state)
480 {
481         struct ast_channel *tmp;
482         struct ast_frame null_frame = { AST_FRAME_NULL };
483 #if 0
484         if (!p->chan) {
485                 ast_log(LOG_WARNING, "No channel? :(\n");
486                 return NULL;
487         }
488 #endif  
489         tmp = ast_channel_alloc(0);
490         if (tmp) {
491                 if (p->chan) {
492                         tmp->nativeformats = p->chan->nativeformats;
493                         tmp->writeformat = p->chan->writeformat;
494                         tmp->pvt->rawwriteformat = p->chan->writeformat;
495                         tmp->readformat = p->chan->readformat;
496                         tmp->pvt->rawreadformat = p->chan->readformat;
497                         strncpy(tmp->language, p->chan->language, sizeof(tmp->language)-1);
498                         strncpy(tmp->context, p->chan->context, sizeof(tmp->context)-1);
499                         strncpy(tmp->exten, p->chan->exten, sizeof(tmp->exten)-1);
500                 } else {
501                         tmp->nativeformats = AST_FORMAT_SLINEAR;
502                         tmp->writeformat = AST_FORMAT_SLINEAR;
503                         tmp->pvt->rawwriteformat = AST_FORMAT_SLINEAR;
504                         tmp->readformat = AST_FORMAT_SLINEAR;
505                         tmp->pvt->rawreadformat = AST_FORMAT_SLINEAR;
506                 }
507                 if (p->pending)
508                         snprintf(tmp->name, sizeof(tmp->name), "Agent/P%s-%d", p->agent, rand() & 0xffff);
509                 else
510                         snprintf(tmp->name, sizeof(tmp->name), "Agent/%s", p->agent);
511                 tmp->type = type;
512                 ast_setstate(tmp, state);
513                 tmp->pvt->pvt = p;
514                 tmp->pvt->send_digit = agent_digit;
515                 tmp->pvt->call = agent_call;
516                 tmp->pvt->hangup = agent_hangup;
517                 tmp->pvt->answer = agent_answer;
518                 tmp->pvt->read = agent_read;
519                 tmp->pvt->write = agent_write;
520                 tmp->pvt->exception = agent_read;
521                 tmp->pvt->indicate = agent_indicate;
522                 tmp->pvt->fixup = agent_fixup;
523                 p->owner = tmp;
524                 ast_pthread_mutex_lock(&usecnt_lock);
525                 usecnt++;
526                 ast_pthread_mutex_unlock(&usecnt_lock);
527                 ast_update_use_count();
528                 tmp->priority = 1;
529                 /* Wake up and wait for other applications (by definition the login app)
530                  * to release this channel). Takes ownership of the agent channel
531                  * to this thread only.
532                  * For signalling the other thread, ast_queue_frame is used until we
533                  * can safely use signals for this purpose. The pselect() needs to be
534                  * implemented in the kernel for this.
535                  */
536                 p->app_sleep_cond = 0;
537                 if( pthread_mutex_trylock(&p->app_lock) )
538                 {
539                         if (p->chan) {
540                                 ast_queue_frame(p->chan, &null_frame, 1);
541                                 ast_pthread_mutex_unlock(&p->lock);     /* For other thread to read the condition. */
542                                 ast_pthread_mutex_lock(&p->app_lock);
543                                 ast_pthread_mutex_lock(&p->lock);
544                         }
545                         if( !p->chan )
546                         {
547                                 ast_log(LOG_WARNING, "Agent disconnected while we were connecting the call\n");
548                                 p->owner = NULL;
549                                 tmp->pvt->pvt = NULL;
550                                 p->app_sleep_cond = 1;
551                                 ast_channel_free( tmp );
552                                 return NULL;
553                         }
554                 }
555                 p->owning_app = pthread_self();
556                 /* After the above step, there should not be any blockers. */
557                 if (p->chan) {
558                         if (p->chan->blocking) {
559                                 ast_log( LOG_ERROR, "A blocker exists after agent channel ownership acquired\n" );
560                                 CRASH;
561                         }
562                         ast_moh_stop(p->chan);
563                 }
564         } else
565                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
566         return tmp;
567 }
568
569
570 static int read_agent_config(void)
571 {
572         struct ast_config *cfg;
573         struct ast_variable *v;
574         struct agent_pvt *p, *pl, *pn;
575         group = 0;
576         autologoff = 0;
577         wrapuptime = 0;
578         cfg = ast_load(config);
579         if (!cfg) {
580                 ast_log(LOG_NOTICE, "No agent configuration found -- agent support disabled\n");
581                 return 0;
582         }
583         ast_pthread_mutex_lock(&agentlock);
584         p = agents;
585         while(p) {
586                 p->dead = 1;
587                 p = p->next;
588         }
589         strcpy(moh, "default");
590         v = ast_variable_browse(cfg, "agents");
591         while(v) {
592                 /* Create the interface list */
593                 if (!strcasecmp(v->name, "agent")) {
594                         add_agent(v->value, 0);
595                 } else if (!strcasecmp(v->name, "group")) {
596                         group = ast_get_group(v->value);
597                 } else if (!strcasecmp(v->name, "autologoff")) {
598                         autologoff = atoi(v->value);
599                         if (autologoff < 0)
600                                 autologoff = 0;
601                 } else if (!strcasecmp(v->name, "wrapuptime")) {
602                         wrapuptime = atoi(v->value);
603                         if (wrapuptime < 0)
604                                 wrapuptime = 0;
605                 } else if (!strcasecmp(v->name, "musiconhold")) {
606                         strncpy(moh, v->value, sizeof(moh) - 1);
607                 }
608                 v = v->next;
609         }
610         p = agents;
611         pl = NULL;
612         while(p) {
613                 pn = p->next;
614                 if (p->dead) {
615                         /* Unlink */
616                         if (pl)
617                                 pl->next = p->next;
618                         else
619                                 agents = p->next;
620                         /* Destroy if  appropriate */
621                         if (!p->owner) {
622                                 if (!p->chan) {
623                                         free(p);
624                                 } else {
625                                         /* Cause them to hang up */
626                                         ast_softhangup(p->chan, AST_SOFTHANGUP_EXPLICIT);
627                                 }
628                         }
629                 } else
630                         pl = p;
631                 p = pn;
632         }
633         ast_pthread_mutex_unlock(&agentlock);
634         ast_destroy(cfg);
635         return 0;
636 }
637
638 static int check_availability(struct agent_pvt *newlyavailable, int needlock)
639 {
640         struct ast_channel *chan=NULL, *parent=NULL;
641         struct agent_pvt *p;
642         int res;
643         ast_log(LOG_DEBUG, "Checking availability of '%s'\n", newlyavailable->agent);
644         if (needlock)
645                 ast_pthread_mutex_lock(&agentlock);
646         p = agents;
647         while(p) {
648                 if (p == newlyavailable) {
649                         p = p->next;
650                         continue;
651                 }
652                 ast_pthread_mutex_lock(&p->lock);
653                 if (!p->abouttograb && p->pending && ((p->group && (newlyavailable->group & p->group)) || !strcmp(p->agent, newlyavailable->agent))) {
654                         ast_log(LOG_DEBUG, "Call '%s' looks like a winner for agent '%s'\n", p->owner->name, newlyavailable->agent);
655                         /* We found a pending call, time to merge */
656                         chan = agent_new(newlyavailable, AST_STATE_DOWN);
657                         parent = p->owner;
658                         p->abouttograb = 1;
659                         ast_pthread_mutex_unlock(&p->lock);
660                         break;
661                 }
662                 ast_pthread_mutex_unlock(&p->lock);
663                 p = p->next;
664         }
665         if (needlock)
666                 ast_pthread_mutex_unlock(&agentlock);
667         if (parent && chan)  {
668                 ast_log( LOG_DEBUG, "Playing beep, lang '%s'\n", newlyavailable->chan->language);
669                 res = ast_streamfile(newlyavailable->chan, "beep", newlyavailable->chan->language);
670                 ast_log( LOG_DEBUG, "Played beep, result '%d'\n", res);
671                 if (!res) {
672                         res = ast_waitstream(newlyavailable->chan, "");
673                         ast_log( LOG_DEBUG, "Waited for stream, result '%d'\n", res);
674                 }
675                 if (!res) {
676                         /* Note -- parent may have disappeared */
677                         if (p->abouttograb) {
678                                 ast_setstate(parent, AST_STATE_UP);
679                                 ast_setstate(chan, AST_STATE_UP);
680                                 /* Go ahead and mark the channel as a zombie so that masquerade will
681                                    destroy it for us, and we need not call ast_hangup */
682                                 ast_pthread_mutex_lock(&parent->lock);
683                                 chan->zombie = 1;
684                                 ast_channel_masquerade(parent, chan);
685                                 ast_pthread_mutex_unlock(&parent->lock);
686                                 p->abouttograb = 0;
687                         } else {
688                                 ast_log(LOG_DEBUG, "Sneaky, parent disappeared in the mean time...\n");
689                                 agent_cleanup(newlyavailable);
690                         }
691                 } else {
692                         ast_log(LOG_DEBUG, "Ugh...  Agent hung up at exactly the wrong time\n");
693                         agent_cleanup(newlyavailable);
694                 }
695         }
696         return 0;
697 }
698
699 static struct ast_channel *agent_request(char *type, int format, void *data)
700 {
701         struct agent_pvt *p;
702         struct ast_channel *chan = NULL;
703         char *s;
704         unsigned int groupmatch;
705         int waitforagent=0;
706         s = data;
707         if ((s[0] == '@') && (sscanf(s + 1, "%d", &groupmatch) == 1)) {
708                 groupmatch = (1 << groupmatch);
709         } else if ((s[0] == ':') && (sscanf(s + 1, "%d", &groupmatch) == 1)) {
710                 groupmatch = (1 << groupmatch);
711                 waitforagent = 1;
712         } else {
713                 groupmatch = 0;
714         }
715         ast_pthread_mutex_lock(&agentlock);
716         p = agents;
717         while(p) {
718                 ast_pthread_mutex_lock(&p->lock);
719                 if (!p->pending && ((groupmatch && (p->group & groupmatch)) || !strcmp(data, p->agent)) &&
720                                 !p->lastdisc.tv_sec) {
721                         /* Agent must be registered, but not have any active call, and not be in a waiting state */
722                         if (!p->owner && p->chan) {
723                                 /* Fixed agent */
724                                 chan = agent_new(p, AST_STATE_DOWN);
725                         } else if (!p->owner && strlen(p->loginchan)) {
726                                 /* Adjustable agent */
727                                 p->chan = ast_request("Local", format, p->loginchan);
728                                 if (p->chan)
729                                         chan = agent_new(p, AST_STATE_DOWN);
730                         }
731                         if (chan) {
732                                 ast_pthread_mutex_unlock(&p->lock);
733                                 break;
734                         }
735                 }
736                 ast_pthread_mutex_unlock(&p->lock);
737                 p = p->next;
738         }
739         if (!chan && waitforagent) {
740                 /* No agent available -- but we're requesting to wait for one.
741                    Allocate a place holder */
742                 ast_log(LOG_DEBUG, "Creating place holder for '%s'\n", s);
743                 p = add_agent(data, 1);
744                 p->group = groupmatch;
745                 chan = agent_new(p, AST_STATE_DOWN);
746                 if (!chan) {
747                         ast_log(LOG_WARNING, "Weird...  Fix this to drop the unused pending agent\n");
748                 }
749         }
750         ast_pthread_mutex_unlock(&agentlock);
751         return chan;
752 }
753
754 static int powerof(unsigned int v)
755 {
756         int x;
757         for (x=0;x<32;x++) {
758                 if (v & (1 << x)) return x;
759         }
760         return 0;
761 }
762
763 static int agents_show(int fd, int argc, char **argv)
764 {
765         struct agent_pvt *p;
766         char username[256];
767         char location[256];
768         char talkingto[256];
769         char moh[256];
770
771         if (argc != 2)
772                 return RESULT_SHOWUSAGE;
773         ast_pthread_mutex_lock(&agentlock);
774         p = agents;
775         while(p) {
776                 ast_pthread_mutex_lock(&p->lock);
777                 if (p->pending) {
778                         if (p->group)
779                                 ast_cli(fd, "-- Pending call to group %d\n", powerof(p->group));
780                         else
781                                 ast_cli(fd, "-- Pending call to agent %s\n", p->agent);
782                 } else {
783                         if (strlen(p->name))
784                                 snprintf(username, sizeof(username), "(%s) ", p->name);
785                         else
786                                 strcpy(username, "");
787                         if (p->chan) {
788                                 snprintf(location, sizeof(location), "logged in on %s", p->chan->name);
789                                 if (p->owner && p->owner->bridge) {
790                                         snprintf(talkingto, sizeof(talkingto), " talking to %s", p->owner->bridge->name);
791                                 } else {
792                                         strcpy(talkingto, " is idle");
793                                 }
794                         } else if (strlen(p->loginchan)) {
795                                 snprintf(location, sizeof(location) - 20, "available at '%s'", p->loginchan);
796                                 strcpy(talkingto, "");
797                                 if (p->acknowledged)
798                                         strcat(location, " (Confirmed)");
799                         } else {
800                                 strcpy(location, "not logged in");
801                                 strcpy(talkingto, "");
802                         }
803                         if (strlen(p->moh))
804                                 snprintf(moh, sizeof(moh), " (musiconhold is '%s')", p->moh);
805                         ast_cli(fd, "%-12.12s %s%s%s%s\n", p->agent, 
806                                         username, location, talkingto, moh);
807                 }
808                 ast_pthread_mutex_unlock(&p->lock);
809                 p = p->next;
810         }
811         ast_pthread_mutex_unlock(&agentlock);
812         return RESULT_SUCCESS;
813 }
814
815 static char show_agents_usage[] = 
816 "Usage: show agents\n"
817 "       Provides summary information on agents.\n";
818
819 static struct ast_cli_entry cli_show_agents = {
820         { "show", "agents", NULL }, agents_show, 
821         "Show status of agents", show_agents_usage, NULL };
822
823 STANDARD_LOCAL_USER;
824 LOCAL_USER_DECL;
825
826 static int __login_exec(struct ast_channel *chan, void *data, int callbackmode)
827 {
828         int res=0;
829         int tries = 0;
830         struct agent_pvt *p;
831         struct localuser *u;
832         struct timeval tv;
833         char user[AST_MAX_AGENT];
834         char pass[AST_MAX_AGENT];
835         char xpass[AST_MAX_AGENT] = "";
836         char *errmsg;
837         char info[512];
838         char *opt_user = NULL;
839         char *options = NULL;
840         char *context = NULL;
841         int play_announcement;
842         char *filename = "agent-loginok";
843         
844         LOCAL_USER_ADD(u);
845
846         /* Parse the arguments XXX Check for failure XXX */
847         strncpy(info, (char *)data, strlen((char *)data) + AST_MAX_EXTENSION-1);
848         opt_user = info;
849         if( opt_user ) {
850                 options = strchr(opt_user, '|');
851                 if (options) {
852                         *options = '\0';
853                         options++;
854                         if (callbackmode) {
855                                 context = strchr(options, '@');
856                                 if (context) {
857                                         *context = '\0';
858                                         context++;
859                                 }
860                         }
861                 }
862         }
863
864         if (chan->_state != AST_STATE_UP)
865                 res = ast_answer(chan);
866         if (!res) {
867                 if( opt_user && strlen(opt_user))
868                         strncpy( user, opt_user, AST_MAX_AGENT );
869                 else
870                         res = ast_app_getdata(chan, "agent-user", user, sizeof(user) - 1, 0);
871         }
872         while (!res && (tries < 3)) {
873                 /* Check for password */
874                 ast_pthread_mutex_lock(&agentlock);
875                 p = agents;
876                 while(p) {
877                         if (!strcmp(p->agent, user) && !p->pending)
878                                 strncpy(xpass, p->password, sizeof(xpass) - 1);
879                         p = p->next;
880                 }
881                 ast_pthread_mutex_unlock(&agentlock);
882                 if (!res) {
883                         if (strlen(xpass))
884                                 res = ast_app_getdata(chan, "agent-pass", pass, sizeof(pass) - 1, 0);
885                         else
886                                 strcpy(pass, "");
887                 }
888                 errmsg = "agent-incorrect";
889
890 #if 0
891                 ast_log(LOG_NOTICE, "user: %s, pass: %s\n", user, pass);
892 #endif          
893
894                 /* Check again for accuracy */
895                 ast_pthread_mutex_lock(&agentlock);
896                 p = agents;
897                 while(p) {
898                         ast_pthread_mutex_lock(&p->lock);
899                         if (!strcmp(p->agent, user) &&
900                                 !strcmp(p->password, pass) && !p->pending) {
901                                         if (!p->chan) {
902                                                 if (callbackmode) {
903                                                         char tmpchan[256] = "";
904                                                         /* Retrieve login chan */
905                                                         res = ast_app_getdata(chan, "agent-newlocation", tmpchan, sizeof(tmpchan) - 1, 0);
906                                                         if (!res) {
907                                                                 if (context && strlen(context))
908                                                                         snprintf(p->loginchan, sizeof(p->loginchan), "%s@%s", tmpchan, context);
909                                                                 else
910                                                                         strncpy(p->loginchan, tmpchan, sizeof(p->loginchan) - 1);
911                                                                 if (!strlen(p->loginchan))
912                                                                         filename = "agent-loggedoff";
913                                                                 p->acknowledged = 0;
914                                                         }
915                                                 } else {
916                                                         strcpy(p->loginchan, "");
917                                                         p->acknowledged = 0;
918                                                 }
919                                                 play_announcement = 1;
920                                                 if( options )
921                                                         if( strchr( options, 's' ) )
922                                                                 play_announcement = 0;
923                                                 if( !res && play_announcement )
924                                                         res = ast_streamfile(chan, filename, chan->language);
925                                                 if (!res)
926                                                         ast_waitstream(chan, "");
927                                                 if (!res) {
928                                                         res = ast_set_read_format(chan, ast_best_codec(chan->nativeformats));
929                                                         if (res)
930                                                                 ast_log(LOG_WARNING, "Unable to set read format to %d\n", ast_best_codec(chan->nativeformats));
931                                                 }
932                                                 if (!res) {
933                                                         ast_set_write_format(chan, ast_best_codec(chan->nativeformats));
934                                                         if (res)
935                                                                 ast_log(LOG_WARNING, "Unable to set write format to %d\n", ast_best_codec(chan->nativeformats));
936                                                 }
937                                                 /* Check once more just in case */
938                                                 if (p->chan)
939                                                         res = -1;
940                                                 if (callbackmode && !res) {
941                                                         /* Just say goodbye and be done with it */
942                                                         if (!res)
943                                                                 res = ast_safe_sleep(chan, 500);
944                                                         res = ast_streamfile(chan, "vm-goodbye", chan->language);
945                                                         if (!res)
946                                                                 res = ast_waitstream(chan, "");
947                                                         if (!res)
948                                                                 res = ast_safe_sleep(chan, 1000);
949                                                         ast_pthread_mutex_unlock(&p->lock);
950                                                         ast_pthread_mutex_unlock(&agentlock);
951                                                 } else if (!res) {
952                                                         /* check if the moh class was changed with setmusiconhold */
953                                                         if (*(chan->musicclass))
954                                                                 strncpy(p->moh, chan->musicclass, sizeof(p->moh) - 1);
955                                                         ast_moh_start(chan, p->moh);
956                                                         manager_event(EVENT_FLAG_AGENT, "Agentlogin",
957                                                                 "Agent: %s\r\n"
958                                                                 "Channel: %s\r\n",
959                                                                 p->agent, chan->name);
960                                                         if (option_verbose > 2)
961                                                                 ast_verbose(VERBOSE_PREFIX_3 "Agent '%s' logged in (format %d/%d)\n", p->agent,
962                                                                                                 chan->readformat, chan->writeformat);
963                                                         /* Login this channel and wait for it to
964                                                            go away */
965                                                         p->chan = chan;
966                                                         p->acknowledged = 1;
967                                                         check_availability(p, 0);
968                                                         ast_pthread_mutex_unlock(&p->lock);
969                                                         ast_pthread_mutex_unlock(&agentlock);
970                                                         while (res >= 0) {
971                                                                 ast_pthread_mutex_lock(&p->lock);
972                                                                 if (p->chan != chan)
973                                                                         res = -1;
974                                                                 ast_pthread_mutex_unlock(&p->lock);
975                                                                 /* Yield here so other interested threads can kick in. */
976                                                                 sched_yield();
977                                                                 if (res)
978                                                                         break;
979
980                                                                 ast_pthread_mutex_lock(&p->lock);
981                                                                 if (p->lastdisc.tv_sec) {
982                                                                         gettimeofday(&tv, NULL);
983                                                                         if ((tv.tv_sec - p->lastdisc.tv_sec) * 1000 + 
984                                                                                 (tv.tv_usec - p->lastdisc.tv_usec) / 1000 > p->wrapuptime) {
985                                                                                         ast_log(LOG_DEBUG, "Wrapup time expired!\n");
986                                                                                 memset(&p->lastdisc, 0, sizeof(p->lastdisc));
987                                                                                 check_availability(p, 1);
988                                                                         }
989                                                                 }
990                                                                 ast_pthread_mutex_unlock(&p->lock);
991                                                                 /*      Synchronize channel ownership between call to agent and itself. */
992                                                                 pthread_mutex_lock( &p->app_lock );
993                                                                 ast_pthread_mutex_lock(&p->lock);
994                                                                 p->owning_app = pthread_self();
995                                                                 ast_pthread_mutex_unlock(&p->lock);
996                                                                 res = ast_safe_sleep_conditional( chan, 1000,
997                                                                                                                 agent_cont_sleep, p );
998                                                                 pthread_mutex_unlock( &p->app_lock );
999                                                                 sched_yield();
1000                                                         }
1001                                                         ast_pthread_mutex_lock(&p->lock);
1002                                                         if (res && p->owner) 
1003                                                                 ast_log(LOG_WARNING, "Huh?  We broke out when there was still an owner?\n");
1004                                                         /* Log us off if appropriate */
1005                                                         if (p->chan == chan)
1006                                                                 p->chan = NULL;
1007                                                         p->acknowledged = 0;
1008                                                         ast_pthread_mutex_unlock(&p->lock);
1009                                                         if (option_verbose > 2)
1010                                                                 ast_verbose(VERBOSE_PREFIX_3 "Agent '%s' logged out\n", p->agent);
1011                                                         manager_event(EVENT_FLAG_AGENT, "Agentlogoff",
1012                                                                 "Agent: %s\r\n",
1013                                                                 p->agent);
1014                                                         /* If there is no owner, go ahead and kill it now */
1015                                                         if (p->dead && !p->owner)
1016                                                                 free(p);
1017                                                 }
1018                                                 else {
1019                                                         ast_pthread_mutex_unlock(&p->lock);
1020                                                         p = NULL;
1021                                                 }
1022                                                 res = -1;
1023                                         } else {
1024                                                 ast_pthread_mutex_unlock(&p->lock);
1025                                                 errmsg = "agent-alreadyon";
1026                                                 p = NULL;
1027                                         }
1028                                         break;
1029                         }
1030                         ast_pthread_mutex_unlock(&p->lock);
1031                         p = p->next;
1032                 }
1033                 if (!p)
1034                         ast_pthread_mutex_unlock(&agentlock);
1035
1036                 if (!res)
1037                         res = ast_app_getdata(chan, errmsg, user, sizeof(user) - 1, 0);
1038         }
1039                 
1040         LOCAL_USER_REMOVE(u);
1041         /* Always hangup */
1042         return -1;
1043 }
1044
1045 static int login_exec(struct ast_channel *chan, void *data)
1046 {
1047         return __login_exec(chan, data, 0);
1048 }
1049
1050 static int callback_exec(struct ast_channel *chan, void *data)
1051 {
1052         return __login_exec(chan, data, 1);
1053 }
1054
1055 int load_module()
1056 {
1057         /* Make sure we can register our sip channel type */
1058         if (ast_channel_register(type, tdesc, capability, agent_request)) {
1059                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1060                 return -1;
1061         }
1062         ast_register_application(app, login_exec, synopsis, descrip);
1063         ast_register_application(app2, callback_exec, synopsis2, descrip2);
1064         ast_cli_register(&cli_show_agents);
1065         /* Read in the config */
1066         read_agent_config();
1067         return 0;
1068 }
1069
1070 int reload()
1071 {
1072         read_agent_config();
1073         return 0;
1074 }
1075
1076 int unload_module()
1077 {
1078         struct agent_pvt *p;
1079         /* First, take us out of the channel loop */
1080         ast_cli_unregister(&cli_show_agents);
1081         ast_unregister_application(app);
1082         ast_unregister_application(app2);
1083         ast_channel_unregister(type);
1084         if (!ast_pthread_mutex_lock(&agentlock)) {
1085                 /* Hangup all interfaces if they have an owner */
1086                 p = agents;
1087                 while(p) {
1088                         if (p->owner)
1089                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1090                         p = p->next;
1091                 }
1092                 agents = NULL;
1093                 ast_pthread_mutex_unlock(&agentlock);
1094         } else {
1095                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1096                 return -1;
1097         }               
1098         return 0;
1099 }
1100
1101 int usecount()
1102 {
1103         int res;
1104         ast_pthread_mutex_lock(&usecnt_lock);
1105         res = usecnt;
1106         ast_pthread_mutex_unlock(&usecnt_lock);
1107         return res;
1108 }
1109
1110 char *key()
1111 {
1112         return ASTERISK_GPL_KEY;
1113 }
1114
1115 char *description()
1116 {
1117         return desc;
1118 }
1119