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