Merge major BSD mutex and symbol conflict patches (bug #1816) (link patch still pending)
[asterisk/asterisk.git] / apps / app_queue.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * True call queues with optional send URL on answer
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * These features added by David C. Troy <dave@toad.net>:
11  *    - Per-queue holdtime calculation
12  *    - Estimated holdtime announcement
13  *    - Position announcement
14  *    - Abandoned/completed call counters
15  *    - Failout timer passed as optional app parameter
16  *    - Optional monitoring of calls, started when call is answered
17  *
18  * Patch Version 1.07 2003-12-24 01
19  *
20  * Added servicelevel statistic by Michiel Betel <michiel@betel.nl>
21  * Added Priority jumping code for adding and removing queue members by Jonathan Stanton <asterisk@doilooklikeicare.com>
22  *
23  * Fixed ot work with CVS as of 2004-02-25 and released as 1.07a
24  * by Matthew Enger <m.enger@xi.com.au>
25  *
26  * This program is free software, distributed under the terms of
27  * the GNU General Public License
28  */
29
30 #include <asterisk/lock.h>
31 #include <asterisk/file.h>
32 #include <asterisk/logger.h>
33 #include <asterisk/channel.h>
34 #include <asterisk/pbx.h>
35 #include <asterisk/options.h>
36 #include <asterisk/module.h>
37 #include <asterisk/translate.h>
38 #include <asterisk/say.h>
39 #include <asterisk/parking.h>
40 #include <asterisk/musiconhold.h>
41 #include <asterisk/cli.h>
42 #include <asterisk/manager.h>
43 #include <asterisk/config.h>
44 #include <asterisk/monitor.h>
45 #include <asterisk/utils.h>
46 #include <stdlib.h>
47 #include <errno.h>
48 #include <unistd.h>
49 #include <string.h>
50 #include <stdlib.h>
51 #include <stdio.h>
52 #include <sys/time.h>
53 #include <sys/signal.h>
54 #include <netinet/in.h>
55
56 #include "../astconf.h"
57
58 #include <pthread.h>
59
60 #define QUEUE_STRATEGY_RINGALL          0
61 #define QUEUE_STRATEGY_ROUNDROBIN       1
62 #define QUEUE_STRATEGY_LEASTRECENT      2
63 #define QUEUE_STRATEGY_FEWESTCALLS      3
64 #define QUEUE_STRATEGY_RANDOM           4
65 #define QUEUE_STRATEGY_RRMEMORY         5
66
67 static struct strategy {
68         int strategy;
69         char *name;
70 } strategies[] = {
71         { QUEUE_STRATEGY_RINGALL, "ringall" },
72         { QUEUE_STRATEGY_ROUNDROBIN, "roundrobin" },
73         { QUEUE_STRATEGY_LEASTRECENT, "leastrecent" },
74         { QUEUE_STRATEGY_FEWESTCALLS, "fewestcalls" },
75         { QUEUE_STRATEGY_RANDOM, "random" },
76         { QUEUE_STRATEGY_RRMEMORY, "rrmemory" },
77 };
78
79 #define DEFAULT_RETRY           5
80 #define DEFAULT_TIMEOUT         15
81 #define RECHECK                         1               /* Recheck every second to see we we're at the top yet */
82
83 static char *tdesc = "True Call Queueing";
84
85 static char *app = "Queue";
86
87 static char *synopsis = "Queue a call for a call queue";
88
89 static char *descrip =
90 "  Queue(queuename[|options[|URL][|announceoverride][|timeout]]):\n"
91 "Queues an incoming call in a particular call queue as defined in queues.conf.\n"
92 "  This application returns -1 if the originating channel hangs up, or if the\n"
93 "call is bridged and  either of the parties in the bridge terminate the call.\n"
94 "Returns 0 if the queue is full, nonexistant, or has no members.\n"
95 "The option string may contain zero or more of the following characters:\n"
96 "      't' -- allow the called user transfer the calling user\n"
97 "      'T' -- to allow the calling user to transfer the call.\n"
98 "      'd' -- data-quality (modem) call (minimum delay).\n"
99 "      'H' -- allow caller to hang up by hitting *.\n"
100 "      'n' -- no retries on the timeout; will exit this application and go to the next step.\n"
101 "      'r' -- ring instead of playing MOH\n"
102 "  In addition to transferring the call, a call may be parked and then picked\n"
103 "up by another user.\n"
104 "  The optional URL will be sent to the called party if the channel supports\n"
105 "it.\n"
106 "  The timeout will cause the queue to fail out after a specified number of\n"
107 "seconds, checked between each queues.conf 'timeout' and 'retry' cycle.\n";
108
109 // [PHM 06/26/03]
110 static char *app_aqm = "AddQueueMember" ;
111 static char *app_aqm_synopsis = "Dynamically adds queue members" ;
112 static char *app_aqm_descrip =
113 "   AddQueueMember(queuename[|interface[|penalty]]):\n"
114 "Dynamically adds interface to an existing queue.\n"
115 "If the interface is already in the queue and there exists an n+101 priority\n"
116 "then it will then jump to this priority.  Otherwise it will return an error\n"
117 "Returns -1 if there is an error.\n"
118 "Example: AddQueueMember(techsupport|SIP/3000)\n"
119 "";
120
121 static char *app_rqm = "RemoveQueueMember" ;
122 static char *app_rqm_synopsis = "Dynamically removes queue members" ;
123 static char *app_rqm_descrip =
124 "   RemoveQueueMember(queuename[|interface]):\n"
125 "Dynamically removes interface to an existing queue\n"
126 "If the interface is NOT in the queue and there exists an n+101 priority\n"
127 "then it will then jump to this priority.  Otherwise it will return an error\n"
128 "Returns -1 if there is an error.\n"
129 "Example: RemoveQueueMember(techsupport|SIP/3000)\n"
130 "";
131
132 /* We define a customer "local user" structure because we
133    use it not only for keeping track of what is in use but
134    also for keeping track of who we're dialing. */
135
136 struct localuser {
137         struct ast_channel *chan;
138         char numsubst[256];
139         char tech[40];
140         int stillgoing;
141         int metric;
142         int allowredirect_in;
143         int allowredirect_out;
144         int ringbackonly;
145         int musiconhold;
146         int dataquality;
147         int allowdisconnect;
148         struct member *member;
149         struct localuser *next;
150 };
151
152 LOCAL_USER_DECL;
153
154 struct queue_ent {
155         struct ast_call_queue *parent;  /* What queue is our parent */
156         char moh[80];                   /* Name of musiconhold to be used */
157         char announce[80];              /* Announcement to play for member when call is answered */
158         char context[80];               /* Context when user exits queue */
159         int pos;                        /* Where we are in the queue */
160         int last_pos_said;              /* Last position we told the user */
161         time_t last_pos;                /* Last time we told the user their position */
162         int opos;                       /* Where we started in the queue */
163         int handled;                    /* Whether our call was handled */
164         time_t start;                   /* When we started holding */
165         int queuetimeout;               /* How many seconds before timing out of queue */
166         struct ast_channel *chan;       /* Our channel */
167         struct queue_ent *next;         /* The next queue entry */
168 };
169
170 struct member {
171         char tech[80];                  /* Technology */
172         char loc[256];                  /* Location */
173         int penalty;                    /* Are we a last resort? */
174         int calls;
175         int dynamic;                    /* Are we dynamically added? */
176         time_t lastcall;                /* When last successful call was hungup */
177         struct member *next;            /* Next member */
178 };
179
180 struct ast_call_queue {
181         ast_mutex_t     lock;   
182         char name[80];                  /* Name of the queue */
183         char moh[80];                   /* Name of musiconhold to be used */
184         char announce[80];              /* Announcement to play when call is answered */
185         char context[80];               /* Context for this queue */
186         int strategy;                   /* Queueing strategy */
187         int announcefrequency;          /* How often to announce their position */
188         int announceholdtime;           /* When to announce holdtime: 0 = never, -1 = every announcement, 1 = only once */
189         int holdtime;                   /* Current avg holdtime for this queue, based on recursive boxcar filter */
190         int callscompleted;             /* Number of queue calls completed */
191         int callsabandoned;             /* Number of queue calls abandoned */
192         int servicelevel;               /* seconds setting for servicelevel*/
193         int callscompletedinsl;         /* Number of queue calls answererd with servicelevel*/
194         char monfmt[8];                 /* Format to use when recording calls */
195         int monjoin;                    /* Should we join the two files when we are done with the call */
196         char sound_next[80];            /* Sound file: "Your call is now first in line" (def. queue-youarenext) */
197         char sound_thereare[80];        /* Sound file: "There are currently" (def. queue-thereare) */
198         char sound_calls[80];           /* Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting)*/
199         char sound_holdtime[80];        /* Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
200         char sound_minutes[80];         /* Sound file: "minutes." (def. queue-minutes) */
201         char sound_thanks[80];          /* Sound file: "Thank you for your patience." (def. queue-thankyou) */
202
203         int count;                      /* How many entries are in the queue */
204         int maxlen;                     /* Max number of entries in queue */
205
206         int dead;                       /* Whether this queue is dead or not */
207         int retry;                      /* Retry calling everyone after this amount of time */
208         int timeout;                    /* How long to wait for an answer */
209         
210         /* Queue strategy things */
211         
212         int rrpos;                      /* Round Robin - position */
213         int wrapped;                    /* Round Robin - wrapped around? */
214
215         struct member *members;         /* Member channels to be tried */
216         struct queue_ent *head;         /* Start of the actual queue */
217         struct ast_call_queue *next;    /* Next call queue */
218 };
219
220 static struct ast_call_queue *queues = NULL;
221 AST_MUTEX_DEFINE_STATIC(qlock);
222
223 static char *int2strat(int strategy)
224 {
225         int x;
226         for (x=0;x<sizeof(strategies) / sizeof(strategies[0]);x++) {
227                 if (strategy == strategies[x].strategy)
228                         return strategies[x].name;
229         }
230         return "<unknown>";
231 }
232
233 static int strat2int(char *strategy)
234 {
235         int x;
236         for (x=0;x<sizeof(strategies) / sizeof(strategies[0]);x++) {
237                 if (!strcasecmp(strategy, strategies[x].name))
238                         return strategies[x].strategy;
239         }
240         return -1;
241 }
242
243 static int join_queue(char *queuename, struct queue_ent *qe)
244 {
245         struct ast_call_queue *q;
246         struct queue_ent *cur, *prev = NULL;
247         int res = -1;
248         int pos = 0;
249         ast_mutex_lock(&qlock);
250         q = queues;
251         while(q) {
252                 if (!strcasecmp(q->name, queuename)) {
253                         /* This is our one */
254                         ast_mutex_lock(&q->lock);
255                         if (q->members && (!q->maxlen || (q->count < q->maxlen))) {
256                                 /* There's space for us, put us at the end */
257                                 prev = NULL;
258                                 cur = q->head;
259                                 while(cur) {
260                                         cur->pos = ++pos;
261                                         prev = cur;
262                                         cur = cur->next;
263                                 }
264                                 if (prev)
265                                         prev->next = qe;
266                                 else
267                                         q->head = qe;
268                                 /* Fix additional pointers and
269                                   information  */
270                                 qe->next = NULL;
271                                 qe->parent = q;
272                                 qe->pos = ++pos;
273                                 qe->opos = pos;
274                                 strncpy(qe->moh, q->moh, sizeof(qe->moh));
275                                 strncpy(qe->announce, q->announce, sizeof(qe->announce));
276                                 strncpy(qe->context, q->context, sizeof(qe->context));
277                                 q->count++;
278                                 res = 0;
279                                 manager_event(EVENT_FLAG_CALL, "Join", 
280                                                                 "Channel: %s\r\nCallerID: %s\r\nQueue: %s\r\nPosition: %d\r\nCount: %d\r\n",
281                                                                 qe->chan->name, (qe->chan->callerid ? qe->chan->callerid : "unknown"), q->name, qe->pos, q->count );
282 #if 0
283 ast_log(LOG_NOTICE, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, qe->chan->name, qe->pos );
284 #endif
285                         }
286                         ast_mutex_unlock(&q->lock);
287                         break;
288                 }
289                 q = q->next;
290         }
291         ast_mutex_unlock(&qlock);
292         return res;
293 }
294
295 static void free_members(struct ast_call_queue *q, int all)
296 {
297         /* Free non-dynamic members */
298         struct member *curm, *next, *prev;
299         curm = q->members;
300         prev = NULL;
301         while(curm) {
302                 next = curm->next;
303                 if (all || !curm->dynamic) {
304                         if (prev)
305                                 prev->next = next;
306                         else
307                                 q->members = next;
308                         free(curm);
309                 } else 
310                         prev = curm;
311                 curm = next;
312         }
313 }
314
315 static void destroy_queue(struct ast_call_queue *q)
316 {
317         struct ast_call_queue *cur, *prev = NULL;
318         ast_mutex_lock(&qlock);
319         cur = queues;
320         while(cur) {
321                 if (cur == q) {
322                         if (prev)
323                                 prev->next = cur->next;
324                         else
325                                 queues = cur->next;
326                 } else {
327                         prev = cur;
328                 }
329                 cur = cur->next;
330         }
331         ast_mutex_unlock(&qlock);
332         free_members(q, 1);
333         ast_mutex_destroy(&q->lock);
334         free(q);
335 }
336
337 static int play_file(struct ast_channel *chan, char *filename)
338 {
339         int res;
340
341         ast_stopstream(chan);
342         res = ast_streamfile(chan, filename, chan->language);
343
344         if (!res)
345                 res = ast_waitstream(chan, "");
346         else
347                 res = 0;
348
349         if (res) {
350                 ast_log(LOG_WARNING, "ast_streamfile failed on %s \n", chan->name);
351                 res = 0;
352         }
353         ast_stopstream(chan);
354
355         return res;
356 }
357
358 static int say_position(struct queue_ent *qe)
359 {
360         int res = 0, avgholdmins;
361         time_t now;
362
363         /* Check to see if this is ludicrous -- if we just announced position, don't do it again*/
364         time(&now);
365         if ( (now - qe->last_pos) < 15 )
366                 return -1;
367
368         /* If either our position has changed, or we are over the freq timer, say position */
369         if ( (qe->last_pos_said == qe->pos) && ((now - qe->last_pos) < qe->parent->announcefrequency) )
370                 return -1;
371
372         ast_moh_stop(qe->chan);
373         /* Say we're next, if we are */
374         if (qe->pos == 1) {
375                 res += play_file(qe->chan, qe->parent->sound_next);
376                 goto posout;
377         } else {
378                 res += play_file(qe->chan, qe->parent->sound_thereare);
379                 res += ast_say_number(qe->chan, qe->pos, AST_DIGIT_ANY, qe->chan->language, (char *) NULL); /* Needs gender */
380                 res += play_file(qe->chan, qe->parent->sound_calls);
381         }
382
383         /* Round hold time to nearest minute */
384         avgholdmins = ( (qe->parent->holdtime + 30) - (now - qe->start) ) / 60;
385         if (option_verbose > 2)
386                 ast_verbose(VERBOSE_PREFIX_3 "Hold time for %s is %d minutes\n", qe->parent->name, avgholdmins);
387
388         /* If the hold time is >1 min, if it's enabled, and if it's not
389            supposed to be only once and we have already said it, say it */
390         if (avgholdmins > 1 && (qe->parent->announceholdtime) && (!(qe->parent->announceholdtime==1 && qe->last_pos)) ) {
391                 res += play_file(qe->chan, qe->parent->sound_holdtime);
392                 res += ast_say_number(qe->chan, avgholdmins, AST_DIGIT_ANY, qe->chan->language, (char*) NULL);
393                 res += play_file(qe->chan, qe->parent->sound_minutes);
394         }
395
396         posout:
397         /* Set our last_pos indicators */
398         qe->last_pos = now;
399         qe->last_pos_said = qe->pos;
400
401         if (option_verbose > 2)
402                 ast_verbose(VERBOSE_PREFIX_3 "Told %s in %s their queue position (which was %d)\n", qe->chan->name, qe->parent->name, qe->pos);
403         res += play_file(qe->chan, qe->parent->sound_thanks);
404         ast_moh_start(qe->chan, qe->moh);
405
406         return (res>0);
407 }
408
409 static void record_abandoned(struct queue_ent *qe)
410 {
411         ast_mutex_lock(&qe->parent->lock);
412         qe->parent->callsabandoned++;
413         ast_mutex_unlock(&qe->parent->lock);
414 }
415
416 static void recalc_holdtime(struct queue_ent *qe)
417 {
418         int oldvalue, newvalue;
419
420         /* Calculate holdtime using a recursive boxcar filter */
421         /* Thanks to SRT for this contribution */
422         /* 2^2 (4) is the filter coefficient; a higher exponent would give old entries more weight */
423
424         newvalue = time(NULL) - qe->start;
425
426         ast_mutex_lock(&qe->parent->lock);
427         if (newvalue <= qe->parent->servicelevel)
428                 qe->parent->callscompletedinsl++;
429         oldvalue = qe->parent->holdtime;
430         qe->parent->holdtime = (((oldvalue << 2) - oldvalue) + newvalue) >> 2;
431         ast_mutex_unlock(&qe->parent->lock);
432 }
433
434
435 static void leave_queue(struct queue_ent *qe)
436 {
437         struct ast_call_queue *q;
438         struct queue_ent *cur, *prev = NULL;
439         int pos = 0;
440         q = qe->parent;
441         if (!q)
442                 return;
443         ast_mutex_lock(&q->lock);
444
445         prev = NULL;
446         cur = q->head;
447         while(cur) {
448                 if (cur == qe) {
449                         q->count--;
450
451                         /* Take us out of the queue */
452                         manager_event(EVENT_FLAG_CALL, "Leave",
453                                  "Channel: %s\r\nQueue: %s\r\nCount: %d\r\n",
454                                  qe->chan->name, q->name,  q->count);
455 #if 0
456 ast_log(LOG_NOTICE, "Queue '%s' Leave, Channel '%s'\n", q->name, qe->chan->name );
457 #endif
458                         /* Take us out of the queue */
459                         if (prev)
460                                 prev->next = cur->next;
461                         else
462                                 q->head = cur->next;
463                 } else {
464                         /* Renumber the people after us in the queue based on a new count */
465                         cur->pos = ++pos;
466                         prev = cur;
467                 }
468                 cur = cur->next;
469         }
470         ast_mutex_unlock(&q->lock);
471         if (q->dead && !q->count) {     
472                 /* It's dead and nobody is in it, so kill it */
473                 destroy_queue(q);
474         }
475 }
476
477 static void hanguptree(struct localuser *outgoing, struct ast_channel *exception)
478 {
479         /* Hang up a tree of stuff */
480         struct localuser *oo;
481         while(outgoing) {
482                 /* Hangup any existing lines we have open */
483                 if (outgoing->chan && (outgoing->chan != exception))
484                         ast_hangup(outgoing->chan);
485                 oo = outgoing;
486                 outgoing=outgoing->next;
487                 free(oo);
488         }
489 }
490
491 static int ring_entry(struct queue_ent *qe, struct localuser *tmp)
492 {
493         int res;
494         /* Request the peer */
495         tmp->chan = ast_request(tmp->tech, qe->chan->nativeformats, tmp->numsubst);
496         if (!tmp->chan) {                       /* If we can't, just go on to the next call */
497 #if 0
498                 ast_log(LOG_NOTICE, "Unable to create channel of type '%s'\n", cur->tech);
499 #endif                  
500                 if (qe->chan->cdr)
501                         ast_cdr_busy(qe->chan->cdr);
502                 tmp->stillgoing = 0;
503                 return 0;
504         }
505         tmp->chan->appl = "AppQueue";
506         tmp->chan->data = "(Outgoing Line)";
507         tmp->chan->whentohangup = 0;
508         if (tmp->chan->callerid)
509                 free(tmp->chan->callerid);
510         if (tmp->chan->ani)
511                 free(tmp->chan->ani);
512         if (qe->chan->callerid)
513                 tmp->chan->callerid = strdup(qe->chan->callerid);
514         else
515                 tmp->chan->callerid = NULL;
516         if (qe->chan->ani)
517                 tmp->chan->ani = strdup(qe->chan->ani);
518         else
519                 tmp->chan->ani = NULL;
520         /* Presense of ADSI CPE on outgoing channel follows ours */
521         tmp->chan->adsicpe = qe->chan->adsicpe;
522         /* Place the call, but don't wait on the answer */
523         res = ast_call(tmp->chan, tmp->numsubst, 0);
524         if (res) {
525                 /* Again, keep going even if there's an error */
526                 if (option_debug)
527                         ast_log(LOG_DEBUG, "ast call on peer returned %d\n", res);
528                 else if (option_verbose > 2)
529                         ast_verbose(VERBOSE_PREFIX_3 "Couldn't call %s\n", tmp->numsubst);
530                 ast_hangup(tmp->chan);
531                 tmp->chan = NULL;
532                 tmp->stillgoing = 0;
533                 return 0;
534         } else
535                 if (option_verbose > 2)
536                         ast_verbose(VERBOSE_PREFIX_3 "Called %s\n", tmp->numsubst);
537         return 0;
538 }
539
540 static int ring_one(struct queue_ent *qe, struct localuser *outgoing)
541 {
542         struct localuser *cur;
543         struct localuser *best;
544         int bestmetric=0;
545         do {
546                 best = NULL;
547                 cur = outgoing;
548                 while(cur) {
549                         if (cur->stillgoing &&                                                  /* Not already done */
550                                 !cur->chan &&                                                           /* Isn't already going */
551                                 (!best || (cur->metric < bestmetric))) {        /* We haven't found one yet, or it's better */
552                                         bestmetric = cur->metric;
553                                         best = cur;
554                         }
555                         cur = cur->next;
556                 }
557                 if (best) {
558                         if (!qe->parent->strategy) {
559                                 /* Ring everyone who shares this best metric (for ringall) */
560                                 cur = outgoing;
561                                 while(cur) {
562                                         if (cur->stillgoing && !cur->chan && (cur->metric == bestmetric)) {
563                                                 ast_log(LOG_DEBUG, "(Parallel) Trying '%s/%s' with metric %d\n", cur->tech, cur->numsubst, cur->metric);
564                                                 ring_entry(qe, cur);
565                                         }
566                                         cur = cur->next;
567                                 }
568                         } else {
569                                 /* Ring just the best channel */
570                                 ast_log(LOG_DEBUG, "Trying '%s/%s' with metric %d\n", best->tech, best->numsubst, best->metric);
571                                 ring_entry(qe, best);
572                         }
573                 }
574         } while (best && !best->chan);
575         if (!best) {
576                 ast_log(LOG_DEBUG, "Nobody left to try ringing in queue\n");
577                 return 0;
578         }
579         return 1;
580 }
581
582 static int store_next(struct queue_ent *qe, struct localuser *outgoing)
583 {
584         struct localuser *cur;
585         struct localuser *best;
586         int bestmetric=0;
587         best = NULL;
588         cur = outgoing;
589         while(cur) {
590                 if (cur->stillgoing &&                                                  /* Not already done */
591                         !cur->chan &&                                                           /* Isn't already going */
592                         (!best || (cur->metric < bestmetric))) {        /* We haven't found one yet, or it's better */
593                                 bestmetric = cur->metric;
594                                 best = cur;
595                 }
596                 cur = cur->next;
597         }
598         if (best) {
599                 /* Ring just the best channel */
600                 ast_log(LOG_DEBUG, "Next is '%s/%s' with metric %d\n", best->tech, best->numsubst, best->metric);
601                 qe->parent->rrpos = best->metric % 1000;
602         } else {
603                 /* Just increment rrpos */
604                 if (!qe->parent->wrapped) {
605                         /* No more channels, start over */
606                         qe->parent->rrpos = 0;
607                 } else {
608                         /* Prioritize next entry */
609                         qe->parent->rrpos++;
610                 }
611         }
612         qe->parent->wrapped = 0;
613         return 0;
614 }
615
616 static int valid_exit(struct queue_ent *qe, char digit)
617 {
618         char tmp[2];
619         if (ast_strlen_zero(qe->context))
620                 return 0;
621         tmp[0] = digit;
622         tmp[1] = '\0';
623         if (ast_exists_extension(qe->chan, qe->context, tmp, 1, qe->chan->callerid)) {
624                 strncpy(qe->chan->context, qe->context, sizeof(qe->chan->context) - 1);
625                 strncpy(qe->chan->exten, tmp, sizeof(qe->chan->exten) - 1);
626                 qe->chan->priority = 0;
627                 return 1;
628         }
629         return 0;
630 }
631
632 #define AST_MAX_WATCHERS 256
633
634 static struct localuser *wait_for_answer(struct queue_ent *qe, struct localuser *outgoing, int *to, int *allowredir_in, int *allowredir_out, int *allowdisconnect, char *digit)
635 {
636         char *queue = qe->parent->name;
637         struct localuser *o;
638         int found;
639         int numlines;
640         int sentringing = 0;
641         int numbusies = 0;
642         int orig = *to;
643         struct ast_frame *f;
644         struct localuser *peer = NULL;
645         struct ast_channel *watchers[AST_MAX_WATCHERS];
646         int pos;
647         struct ast_channel *winner;
648         struct ast_channel *in = qe->chan;
649         
650         while(*to && !peer) {
651                 o = outgoing;
652                 found = -1;
653                 pos = 1;
654                 numlines = 0;
655                 watchers[0] = in;
656                 while(o) {
657                         /* Keep track of important channels */
658                         if (o->stillgoing && o->chan) {
659                                 watchers[pos++] = o->chan;
660                                 found = 1;
661                         }
662                         o = o->next;
663                         numlines++;
664                 }
665                 if (found < 0) {
666                         if (numlines == numbusies) {
667                                 ast_log(LOG_DEBUG, "Everyone is busy at this time\n");
668                         } else {
669                                 ast_log(LOG_NOTICE, "No one is answering queue '%s'\n", queue);
670                         }
671                         *to = 0;
672                         return NULL;
673                 }
674                 winner = ast_waitfor_n(watchers, pos, to);
675                 o = outgoing;
676                 while(o) {
677                         if (o->stillgoing && (o->chan) &&  (o->chan->_state == AST_STATE_UP)) {
678                                 if (!peer) {
679                                         if (option_verbose > 2)
680                                                 ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
681                                         peer = o;
682                                         *allowredir_in = o->allowredirect_in;
683                                         *allowredir_out = o->allowredirect_out;
684                                         *allowdisconnect = o->allowdisconnect;
685                                 }
686                         } else if (o->chan && (o->chan == winner)) {
687                                 f = ast_read(winner);
688                                 if (f) {
689                                         if (f->frametype == AST_FRAME_CONTROL) {
690                                                 switch(f->subclass) {
691                                             case AST_CONTROL_ANSWER:
692                                                         /* This is our guy if someone answered. */
693                                                         if (!peer) {
694                                                                 if (option_verbose > 2)
695                                                                         ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
696                                                                 peer = o;
697                                                                 *allowredir_in = o->allowredirect_in;
698                                                                 *allowredir_out = o->allowredirect_out;
699                                                                 *allowdisconnect = o->allowdisconnect;
700                                                         }
701                                                         break;
702                                                 case AST_CONTROL_BUSY:
703                                                         if (option_verbose > 2)
704                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is busy\n", o->chan->name);
705                                                         o->stillgoing = 0;
706                                                         if (in->cdr)
707                                                                 ast_cdr_busy(in->cdr);
708                                                         ast_hangup(o->chan);
709                                                         o->chan = NULL;
710                                                         if (qe->parent->strategy)
711                                                                 ring_one(qe, outgoing);
712                                                         numbusies++;
713                                                         break;
714                                                 case AST_CONTROL_CONGESTION:
715                                                         if (option_verbose > 2)
716                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is circuit-busy\n", o->chan->name);
717                                                         o->stillgoing = 0;
718                                                         if (in->cdr)
719                                                                 ast_cdr_busy(in->cdr);
720                                                         ast_hangup(o->chan);
721                                                         o->chan = NULL;
722                                                         if (qe->parent->strategy)
723                                                                 ring_one(qe, outgoing);
724                                                         numbusies++;
725                                                         break;
726                                                 case AST_CONTROL_RINGING:
727                                                         if (option_verbose > 2)
728                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is ringing\n", o->chan->name);
729                                                         if (!sentringing) {
730 #if 0
731                                                                 ast_indicate(in, AST_CONTROL_RINGING);
732 #endif                                                          
733                                                                 sentringing++;
734                                                         }
735                                                         break;
736                                                 case AST_CONTROL_OFFHOOK:
737                                                         /* Ignore going off hook */
738                                                         break;
739                                                 default:
740                                                         ast_log(LOG_DEBUG, "Dunno what to do with control type %d\n", f->subclass);
741                                                 }
742                                         }
743                                         ast_frfree(f);
744                                 } else {
745                                         o->stillgoing = 0;
746                                         ast_hangup(o->chan);
747                                         o->chan = NULL;
748                                         if (qe->parent->strategy)
749                                                 ring_one(qe, outgoing);
750                                 }
751                         }
752                         o = o->next;
753                 }
754                 if (winner == in) {
755                         f = ast_read(in);
756 #if 0
757                         if (f && (f->frametype != AST_FRAME_VOICE))
758                                         printf("Frame type: %d, %d\n", f->frametype, f->subclass);
759                         else if (!f || (f->frametype != AST_FRAME_VOICE))
760                                 printf("Hangup received on %s\n", in->name);
761 #endif
762                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))) {
763                                 /* Got hung up */
764                                 *to=-1;
765                                 return NULL;
766                         }
767                         if (f && (f->frametype == AST_FRAME_DTMF) && allowdisconnect && (f->subclass == '*')) {
768                             if (option_verbose > 3)
769                                         ast_verbose(VERBOSE_PREFIX_3 "User hit %c to disconnect call.\n", f->subclass);
770                                 *to=0;
771                                 return NULL;
772                         }
773                         if (f && (f->frametype == AST_FRAME_DTMF) && (f->subclass != '*') && valid_exit(qe, f->subclass)) {
774                                 if (option_verbose > 3)
775                                         ast_verbose(VERBOSE_PREFIX_3 "User pressed digit: %c", f->subclass);
776                                 *to=0;
777                                 *digit=f->subclass;
778                                 return NULL;
779                         }
780                 }
781                 if (!*to && (option_verbose > 2))
782                         ast_verbose( VERBOSE_PREFIX_3 "Nobody picked up in %d ms\n", orig);
783         }
784
785         return peer;
786         
787 }
788
789 static int wait_our_turn(struct queue_ent *qe, int ringing)
790 {
791         struct queue_ent *ch;
792         int res = 0;
793         time_t now;
794
795         /* This is the holding pen for callers 2 through maxlen */
796         for (;;) {
797                 /* Atomically read the parent head -- does not need a lock */
798                 ch = qe->parent->head;
799
800                 /* If we are now at the top of the head, break out */
801                 if (qe == ch)
802                         break;
803
804                 /* If we have timed out, break out */
805                 if ( qe->queuetimeout ) {
806                         time(&now);
807                         if ( (now - qe->start) >= qe->queuetimeout )
808                         break;
809                 }
810
811                 /* Make a position announcement, if enabled */
812                 if (qe->parent->announcefrequency && !ringing)
813                         say_position(qe);
814
815
816                 /* Wait a second before checking again */
817                 res = ast_waitfordigit(qe->chan, RECHECK * 1000);
818                 if (res)
819                         break;
820         }
821         return res;
822 }
823
824 static int update_queue(struct ast_call_queue *q, struct member *member)
825 {
826         struct member *cur;
827         /* Since a reload could have taken place, we have to traverse the list to
828                 be sure it's still valid */
829         ast_mutex_lock(&q->lock);
830         cur = q->members;
831         while(cur) {
832                 if (member == cur) {
833                         time(&cur->lastcall);
834                         cur->calls++;
835                         break;
836                 }
837                 cur = cur->next;
838         }
839         q->callscompleted++;
840         ast_mutex_unlock(&q->lock);
841         return 0;
842 }
843
844 static int calc_metric(struct ast_call_queue *q, struct member *mem, int pos, struct queue_ent *qe, struct localuser *tmp)
845 {
846         switch (q->strategy) {
847         case QUEUE_STRATEGY_RINGALL:
848                 /* Everyone equal, except for penalty */
849                 tmp->metric = mem->penalty * 1000000;
850                 break;
851         case QUEUE_STRATEGY_ROUNDROBIN:
852                 if (!pos) {
853                         if (!q->wrapped) {
854                                 /* No more channels, start over */
855                                 q->rrpos = 0;
856                         } else {
857                                 /* Prioritize next entry */
858                                 q->rrpos++;
859                         }
860                         q->wrapped = 0;
861                 }
862                 /* Fall through */
863         case QUEUE_STRATEGY_RRMEMORY:
864                 if (pos < q->rrpos) {
865                         tmp->metric = 1000 + pos;
866                 } else {
867                         if (pos > q->rrpos) {
868                                 /* Indicate there is another priority */
869                                 q->wrapped = 1;
870                         }
871                         tmp->metric = pos;
872                 }
873                 tmp->metric += mem->penalty * 1000000;
874                 break;
875         case QUEUE_STRATEGY_RANDOM:
876                 tmp->metric = rand() % 1000;
877                 tmp->metric += mem->penalty * 1000000;
878                 break;
879         case QUEUE_STRATEGY_FEWESTCALLS:
880                 tmp->metric = mem->calls;
881                 tmp->metric += mem->penalty * 1000000;
882                 break;
883         case QUEUE_STRATEGY_LEASTRECENT:
884                 if (!mem->lastcall)
885                         tmp->metric = 0;
886                 else
887                         tmp->metric = 1000000 - (time(NULL) - mem->lastcall);
888                 tmp->metric += mem->penalty * 1000000;
889                 break;
890         default:
891                 ast_log(LOG_WARNING, "Can't calculate metric for unknown strategy %d\n", q->strategy);
892                 break;
893         }
894         return 0;
895 }
896
897 static int try_calling(struct queue_ent *qe, char *options, char *announceoverride, char *url, int *go_on)
898 {
899         struct member *cur;
900         struct localuser *outgoing=NULL, *tmp = NULL;
901         int to;
902         int allowredir_in=0;
903         int allowredir_out=0;
904         int allowdisconnect=0;
905         char restofit[AST_MAX_EXTENSION];
906         char oldexten[AST_MAX_EXTENSION]="";
907         char oldcontext[AST_MAX_EXTENSION]="";
908         char queuename[256]="";
909         char *newnum;
910         char *monitorfilename;
911         struct ast_channel *peer;
912         struct localuser *lpeer;
913         struct member *member;
914         int res = 0, bridge = 0;
915         int zapx = 2;
916         int x=0;
917         char *announce = NULL;
918         char digit = 0;
919         time_t callstart;
920         time_t now;
921         struct ast_bridge_config config;
922         /* Hold the lock while we setup the outgoing calls */
923         ast_mutex_lock(&qe->parent->lock);
924         strncpy(queuename, qe->parent->name, sizeof(queuename) - 1);
925         time(&now);
926         cur = qe->parent->members;
927         if (!ast_strlen_zero(qe->announce))
928                 announce = qe->announce;
929         if (announceoverride && !ast_strlen_zero(announceoverride))
930                 announce = announceoverride;
931         while(cur) {
932                 /* Get a technology/[device:]number pair */
933                 tmp = malloc(sizeof(struct localuser));
934                 if (!tmp) {
935                         ast_mutex_unlock(&qe->parent->lock);
936                         ast_log(LOG_WARNING, "Out of memory\n");
937                         goto out;
938                 }
939                 memset(tmp, 0, sizeof(struct localuser));
940                 tmp->stillgoing = -1;
941                 if (options) {
942                         if (strchr(options, 't'))
943                                 tmp->allowredirect_in = 1;
944                         if (strchr(options, 'T'))
945                                 tmp->allowredirect_out = 1;
946                         if (strchr(options, 'r'))
947                                 tmp->ringbackonly = 1;
948                         if (strchr(options, 'm'))
949                                 tmp->musiconhold = 1;
950                         if (strchr(options, 'd'))
951                                 tmp->dataquality = 1;
952                         if (strchr(options, 'H'))
953                                 tmp->allowdisconnect = 1;
954                         if ((strchr(options, 'n')) && (now - qe->start >= qe->parent->timeout))
955                                 *go_on = 1;
956                 }
957                 if (url) {
958                         ast_log(LOG_DEBUG, "Queue with URL=%s_\n", url);
959                 } else 
960                         ast_log(LOG_DEBUG, "Simple queue (no URL)\n");
961
962                 tmp->member = cur;              /* Never directly dereference!  Could change on reload */
963                 strncpy(tmp->tech, cur->tech, sizeof(tmp->tech)-1);
964                 strncpy(tmp->numsubst, cur->loc, sizeof(tmp->numsubst)-1);
965                 /* If we're dialing by extension, look at the extension to know what to dial */
966                 if ((newnum = strstr(tmp->numsubst, "BYEXTENSION"))) {
967                         strncpy(restofit, newnum + strlen("BYEXTENSION"), sizeof(restofit)-1);
968                         snprintf(newnum, sizeof(tmp->numsubst) - (newnum - tmp->numsubst), "%s%s", qe->chan->exten,restofit);
969                         if (option_debug)
970                                 ast_log(LOG_DEBUG, "Dialing by extension %s\n", tmp->numsubst);
971                 }
972                 /* Special case: If we ring everyone, go ahead and ring them, otherwise
973                    just calculate their metric for the appropriate strategy */
974                 calc_metric(qe->parent, cur, x++, qe, tmp);
975                 /* Put them in the list of outgoing thingies...  We're ready now. 
976                    XXX If we're forcibly removed, these outgoing calls won't get
977                    hung up XXX */
978                 tmp->next = outgoing;
979                 outgoing = tmp;         
980                 /* If this line is up, don't try anybody else */
981                 if (outgoing->chan && (outgoing->chan->_state == AST_STATE_UP))
982                         break;
983
984                 cur = cur->next;
985         }
986         if (qe->parent->timeout)
987                 to = qe->parent->timeout * 1000;
988         else
989                 to = -1;
990         ring_one(qe, outgoing);
991         ast_mutex_unlock(&qe->parent->lock);
992         lpeer = wait_for_answer(qe, outgoing, &to, &allowredir_in, &allowredir_out, &allowdisconnect, &digit);
993         ast_mutex_lock(&qe->parent->lock);
994         if (qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY) {
995                 store_next(qe, outgoing);
996         }
997         ast_mutex_unlock(&qe->parent->lock);
998         if (lpeer)
999                 peer = lpeer->chan;
1000         else
1001                 peer = NULL;
1002         if (!peer) {
1003                 if (to) {
1004                         /* Musta gotten hung up */
1005                         record_abandoned(qe);
1006                         res = -1;
1007                 } else {
1008                         if (digit && valid_exit(qe, digit))
1009                                 res=digit;
1010                         else
1011                                 /* Nobody answered, next please? */
1012                                 res=0;
1013                 }
1014                 goto out;
1015         }
1016         if (peer) {
1017                 /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
1018                    we will always return with -1 so that it is hung up properly after the 
1019                    conversation.  */
1020                 qe->handled++;
1021                 if (!strcmp(qe->chan->type,"Zap")) {
1022                         if (tmp->dataquality) zapx = 0;
1023                         ast_channel_setoption(qe->chan,AST_OPTION_TONE_VERIFY,&zapx,sizeof(char),0);
1024                 }                       
1025                 if (!strcmp(peer->type,"Zap")) {
1026                         if (tmp->dataquality) zapx = 0;
1027                         ast_channel_setoption(peer,AST_OPTION_TONE_VERIFY,&zapx,sizeof(char),0);
1028                 }
1029                 /* Update parameters for the queue */
1030                 recalc_holdtime(qe);
1031                 member = lpeer->member;
1032                 hanguptree(outgoing, peer);
1033                 outgoing = NULL;
1034                 if (announce) {
1035                         int res2;
1036                         res2 = ast_autoservice_start(qe->chan);
1037                         if (!res2) {
1038                                 res2 = ast_streamfile(peer, announce, peer->language);
1039                                 if (!res2)
1040                                         res2 = ast_waitstream(peer, "");
1041                                 else {
1042                                         ast_log(LOG_WARNING, "Announcement file '%s' is unavailable, continuing anyway...\n", announce);
1043                                         res2 = 0;
1044                                 }
1045                         }
1046                         res2 |= ast_autoservice_stop(qe->chan);
1047                         if (res2) {
1048                                 /* Agent must have hung up */
1049                                 ast_log(LOG_WARNING, "Agent on %s hungup on the customer.  They're going to be pissed.\n", peer->name);
1050                                 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "AGENTDUMP", "%s", "");
1051                                 ast_hangup(peer);
1052                                 return -1;
1053                         }
1054                 }
1055                 /* Stop music on hold */
1056                 ast_moh_stop(qe->chan);
1057                 /* If appropriate, log that we have a destination channel */
1058                 if (qe->chan->cdr)
1059                         ast_cdr_setdestchan(qe->chan->cdr, peer->name);
1060                 /* Make sure channels are compatible */
1061                 res = ast_channel_make_compatible(qe->chan, peer);
1062                 if (res < 0) {
1063                         ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "SYSCOMPAT", "%s", "");
1064                         ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", qe->chan->name, peer->name);
1065                         ast_hangup(peer);
1066                         return -1;
1067                 }
1068                 /* Begin Monitoring */
1069                 if (qe->parent->monfmt && *qe->parent->monfmt) {
1070                         monitorfilename = pbx_builtin_getvar_helper( qe->chan, "MONITOR_FILENAME");
1071                         if(monitorfilename) {
1072                                 ast_monitor_start( peer, qe->parent->monfmt, monitorfilename, 1 );
1073                         } else {
1074                                 ast_monitor_start( peer, qe->parent->monfmt, qe->chan->cdr->uniqueid, 1 );
1075                         }
1076                         if(qe->parent->monjoin) {
1077                                 ast_monitor_setjoinfiles( peer, 1);
1078                         }
1079                 }
1080                 /* Drop out of the queue at this point, to prepare for next caller */
1081                 leave_queue(qe);                        
1082                 if( url && !ast_strlen_zero(url) && ast_channel_supports_html(peer) ) {
1083                         ast_log(LOG_DEBUG, "app_queue: sendurl=%s.\n", url);
1084                         ast_channel_sendurl( peer, url );
1085                 }
1086                 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "CONNECT", "%ld", (long)time(NULL) - qe->start);
1087                 strncpy(oldcontext, qe->chan->context, sizeof(oldcontext) - 1);
1088                 strncpy(oldexten, qe->chan->exten, sizeof(oldexten) - 1);
1089                 time(&callstart);
1090
1091                 memset(&config,0,sizeof(struct ast_bridge_config));
1092         config.allowredirect_in = allowredir_in;
1093         config.allowredirect_out = allowredir_out;
1094         config.allowdisconnect = allowdisconnect;
1095         bridge = ast_bridge_call(qe->chan,peer,&config);
1096
1097                 if (strcasecmp(oldcontext, qe->chan->context) || strcasecmp(oldexten, qe->chan->exten)) {
1098                         ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "TRANSFER", "%s|%s", qe->chan->exten, qe->chan->context);
1099                 } else if (qe->chan->_softhangup) {
1100                         ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "COMPLETECALLER", "%ld|%ld", (long)(callstart - qe->start), (long)(time(NULL) - callstart));
1101                 } else {
1102                         ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "COMPLETEAGENT", "%ld|%ld", (long)(callstart - qe->start), (long)(time(NULL) - callstart));
1103                 }
1104
1105                 if(bridge != AST_PBX_NO_HANGUP_PEER)
1106                         ast_hangup(peer);
1107                 update_queue(qe->parent, member);
1108                 if( bridge == 0 ) res=1; /* JDG: bridge successfull, leave app_queue */
1109                 else res = bridge; /* bridge error, stay in the queue */
1110         }       
1111 out:
1112         hanguptree(outgoing, NULL);
1113         return res;
1114 }
1115
1116 static int wait_a_bit(struct queue_ent *qe)
1117 {
1118         /* Don't need to hold the lock while we setup the outgoing calls */
1119         int retrywait = qe->parent->retry * 1000;
1120         return ast_waitfordigit(qe->chan, retrywait);
1121 }
1122
1123 // [PHM 06/26/03]
1124
1125 static struct member * interface_exists( struct ast_call_queue * q, char * interface )
1126 {
1127         struct member * ret = NULL ;
1128         struct member *mem;
1129         char buf[500] ;
1130
1131         if( q != NULL )
1132         {
1133                 mem = q->members ;
1134
1135                 while( mem != NULL ) {
1136                         sprintf( buf, "%s/%s", mem->tech, mem->loc);
1137
1138                         if( strcmp( buf, interface ) == 0 ) {
1139                                 ret = mem ;
1140                                 break ;
1141                         }
1142                         else
1143                                 mem = mem->next ;
1144                 }
1145         }
1146
1147         return( ret ) ;
1148 }
1149
1150
1151 static struct member * create_queue_node( char * interface, int penalty )
1152 {
1153         struct member * cur ;
1154         char * tmp ;
1155         
1156         /* Add a new member */
1157
1158         cur = malloc(sizeof(struct member));
1159
1160         if (cur) {
1161                 memset(cur, 0, sizeof(struct member));
1162                 cur->penalty = penalty;
1163                 strncpy(cur->tech, interface, sizeof(cur->tech) - 1);
1164                 if ((tmp = strchr(cur->tech, '/')))
1165                         *tmp = '\0';
1166                 if ((tmp = strchr(interface, '/'))) {
1167                         tmp++;
1168                         strncpy(cur->loc, tmp, sizeof(cur->loc) - 1);
1169                 } else
1170                         ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
1171         }
1172
1173         return( cur ) ;
1174 }
1175
1176
1177 static int rqm_exec(struct ast_channel *chan, void *data)
1178 {
1179         int res=-1;
1180         struct localuser *u;
1181         char *queuename;
1182         struct member * node ;
1183         struct member * look ;
1184         char info[512];
1185         char tmpchan[256]="";
1186         char *interface=NULL;
1187         struct ast_call_queue *q;
1188         int found=0 ;
1189
1190         if (!data) {
1191                 ast_log(LOG_WARNING, "RemoveQueueMember requires an argument (queuename|optional interface)\n");
1192                 return -1;
1193         }
1194         
1195         LOCAL_USER_ADD(u); // not sure if we need this, but better be safe than sorry ;-)
1196         
1197         /* Parse our arguments XXX Check for failure XXX */
1198         strncpy(info, (char *)data, strlen((char *)data) + AST_MAX_EXTENSION-1);
1199         queuename = info;
1200         if (queuename) {
1201                 interface = strchr(queuename, '|');
1202                 if (interface) {
1203                         *interface = '\0';
1204                         interface++;
1205                 }
1206                 else {
1207                         strncpy(tmpchan, chan->name, sizeof(tmpchan) - 1);
1208                         interface = strrchr(tmpchan, '-');
1209                         if (interface)
1210                                 *interface = '\0';
1211                         interface = tmpchan;
1212                 }
1213         }
1214
1215         if( ( q = queues) != NULL )
1216         {
1217                 while( q && ( res != 0 ) && (!found) ) 
1218                 {
1219                         ast_mutex_lock(&q->lock);
1220                         if( strcmp( q->name, queuename) == 0 )
1221                         {
1222                                 // found queue, try to remove  interface
1223                                 found=1 ;
1224
1225                                 if( ( node = interface_exists( q, interface ) ) != NULL )
1226                                 {
1227                                         if( ( look = q->members ) == node )
1228                                         {
1229                                                 // 1st
1230                                                 q->members = node->next;
1231                                         }
1232                                         else
1233                                         {
1234                                                 while( look != NULL )
1235                                                         if( look->next == node )
1236                                                         {
1237                                                                 look->next = node->next ;
1238                                                                 break ;
1239                                                         }
1240                                                         else
1241                                                                 look = look->next ;
1242                                         }
1243
1244                                         free( node ) ;
1245
1246                                         ast_log(LOG_NOTICE, "Removed interface '%s' to queue '%s'\n", 
1247                                                 interface, queuename);
1248                                         res = 0 ;
1249                                 }
1250                                 else
1251                                 {
1252                                         ast_log(LOG_WARNING, "Unable to remove interface '%s' from queue '%s': "
1253                                                 "Not there\n", interface, queuename);
1254                                         if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 101, chan->callerid))
1255                                                 {
1256                                                 chan->priority += 100;
1257                                                 res = 0 ;
1258                                                 }
1259                                 }
1260                         }
1261
1262                         ast_mutex_unlock(&q->lock);
1263                         q = q->next;
1264                 }
1265         }
1266
1267         if( ! found )
1268                 ast_log(LOG_WARNING, "Unable to remove interface from queue '%s': No such queue\n", queuename);
1269
1270         LOCAL_USER_REMOVE(u);
1271         return res;
1272 }
1273
1274
1275
1276 static int aqm_exec(struct ast_channel *chan, void *data)
1277 {
1278         int res=-1;
1279         struct localuser *u;
1280         char *queuename;
1281         char info[512];
1282         char tmpchan[512]="";
1283         char *interface=NULL;
1284         char *penaltys=NULL;
1285         int penalty = 0;
1286         struct ast_call_queue *q;
1287         struct member *save;
1288         int found=0 ;
1289
1290         if (!data) {
1291                 ast_log(LOG_WARNING, "AddQueueMember requires an argument (queuename|optional interface|optional penalty)\n");
1292                 return -1;
1293         }
1294         
1295         LOCAL_USER_ADD(u); // not sure if we need this, but better be safe than sorry ;-)
1296         
1297         /* Parse our arguments XXX Check for failure XXX */
1298         strncpy(info, (char *)data, strlen((char *)data) + AST_MAX_EXTENSION-1);
1299         queuename = info;
1300         if (queuename) {
1301                 interface = strchr(queuename, '|');
1302                 if (interface) {
1303                         *interface = '\0';
1304                         interface++;
1305                 }
1306                 if (interface) {
1307                         penaltys = strchr(interface, '|');
1308                         if (penaltys) {
1309                                 *penaltys = 0;
1310                                 penaltys++;
1311                         }
1312                 }
1313                 if (!interface || !strlen(interface)) {
1314                         strncpy(tmpchan, chan->name, sizeof(tmpchan) - 1);
1315                         interface = strrchr(tmpchan, '-');
1316                         if (interface)
1317                                 *interface = '\0';
1318                         interface = tmpchan;
1319                 }
1320                 if (penaltys && strlen(penaltys)) {
1321                         if ((sscanf(penaltys, "%d", &penalty) != 1) || penalty < 0) {
1322                                 ast_log(LOG_WARNING, "Penalty '%s' is invalid, must be an integer >= 0\n", penaltys);
1323                                 penalty = 0;
1324                         }
1325                 }
1326         }
1327
1328         if( ( q = queues) != NULL )
1329         {
1330                 while( q && ( res != 0 ) && (!found) ) 
1331                 {
1332                         ast_mutex_lock(&q->lock);
1333                         if( strcmp( q->name, queuename) == 0 )
1334                         {
1335                                 // found queue, try to enable interface
1336                                 found=1 ;
1337
1338                                 if( interface_exists( q, interface ) == NULL )
1339                                 {
1340                                         save = q->members ;
1341                                         q->members = create_queue_node( interface, penalty ) ;
1342
1343                                         if( q->members != NULL ) {
1344                                                 q->members->dynamic = 1;
1345                                                 q->members->next = save ;
1346                                         } else
1347                                                 q->members = save ;
1348
1349                                         ast_log(LOG_NOTICE, "Added interface '%s' to queue '%s'\n", interface, queuename);
1350                                         res = 0 ;
1351                                 }
1352                                 else
1353                                 {
1354                                         ast_log(LOG_WARNING, "Unable to add interface '%s' to queue '%s': "
1355                                                 "Already there\n", interface, queuename);
1356                                         if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 101, chan->callerid))
1357                                         {
1358                                                 chan->priority += 100;
1359                                                 res = 0 ;
1360                                         }
1361                                 }
1362                         }
1363
1364                         ast_mutex_unlock(&q->lock);
1365                         q = q->next;
1366                 }
1367         }
1368
1369         if( ! found )
1370                 ast_log(LOG_WARNING, "Unable to add interface to queue '%s': No such queue\n", queuename);
1371
1372         LOCAL_USER_REMOVE(u);
1373         return res;
1374 }
1375
1376
1377 static int queue_exec(struct ast_channel *chan, void *data)
1378 {
1379         int res=-1;
1380         int ringing=0;
1381         struct localuser *u;
1382         char *queuename;
1383         char info[512];
1384         char *options = NULL;
1385         char *url = NULL;
1386         char *announceoverride = NULL;
1387         char *queuetimeoutstr = NULL;
1388         /* whether to exit Queue application after the timeout hits */
1389         int go_on = 0;
1390
1391
1392
1393         /* Our queue entry */
1394         struct queue_ent qe;
1395         
1396         if (!data) {
1397                 ast_log(LOG_WARNING, "Queue requires an argument (queuename|optional timeout|optional URL)\n");
1398                 return -1;
1399         }
1400         
1401         LOCAL_USER_ADD(u);
1402
1403         /* Setup our queue entry */
1404         memset(&qe, 0, sizeof(qe));
1405         
1406         /* Parse our arguments XXX Check for failure XXX */
1407         strncpy(info, (char *)data, strlen((char *)data) + AST_MAX_EXTENSION-1);
1408         queuename = info;
1409         if (queuename) {
1410                 options = strchr(queuename, '|');
1411                 if (options) {
1412                         *options = '\0';
1413                         options++;
1414                         url = strchr(options, '|');
1415                         if (url) {
1416                                 *url = '\0';
1417                                 url++;
1418                                 announceoverride = strchr(url, '|');
1419                                 if (announceoverride) {
1420                                         *announceoverride = '\0';
1421                                         announceoverride++;
1422                                         queuetimeoutstr = strchr(announceoverride, '|');
1423                                         if (queuetimeoutstr) {
1424                                                 *queuetimeoutstr = '\0';
1425                                                 queuetimeoutstr++;
1426                                                 qe.queuetimeout = atoi(queuetimeoutstr);
1427                                         } else {
1428                                                 qe.queuetimeout = 0;
1429                                 }
1430                         }
1431                 }
1432         }
1433         }
1434
1435         if (options) {
1436                 if (strchr(options, 'r')) {
1437                         ringing = 1;
1438                 }
1439         }
1440
1441         printf("queue: %s, options: %s, url: %s, announce: %s, timeout: %d\n",
1442                 queuename, options, url, announceoverride, qe.queuetimeout);
1443
1444
1445         qe.chan = chan;
1446         qe.start = time(NULL);
1447         qe.last_pos_said = 0;
1448         qe.last_pos = 0;
1449         if (!join_queue(queuename, &qe)) {
1450                 ast_queue_log(queuename, chan->uniqueid, "NONE", "ENTERQUEUE", "%s|%s", url ? url : "", chan->callerid ? chan->callerid : "");
1451                 /* Start music on hold */
1452                 if (ringing) {
1453                         ast_indicate(chan, AST_CONTROL_RINGING);
1454                 } else {              
1455                         ast_moh_start(chan, qe.moh);
1456                 }
1457                 for (;;) {
1458                         /* This is the wait loop for callers 2 through maxlen */
1459
1460                         res = wait_our_turn(&qe, ringing);
1461                         /* If they hungup, return immediately */
1462                         if (res < 0) {
1463                                 /* Record this abandoned call */
1464                                 record_abandoned(&qe);
1465                                 ast_queue_log(queuename, chan->uniqueid, "NONE", "ABANDON", "%d|%d|%ld", qe.pos, qe.opos, (long)time(NULL) - qe.start);
1466                                 if (option_verbose > 2) {
1467                                         ast_verbose(VERBOSE_PREFIX_3 "User disconnected while waiting their turn\n");
1468                                         res = -1;
1469                                 }
1470                                 break;
1471                         }
1472                         if (!res) 
1473                                 break;
1474                         if (valid_exit(&qe, res)) {
1475                                 ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHKEY", "%c|%d", res, qe.pos);
1476                                 break;
1477                         }
1478                 }
1479                 if (!res) {
1480                         for (;;) {
1481                                 /* This is the wait loop for the head caller*/
1482                                 /* To exit, they may get their call answered; */
1483                                 /* they may dial a digit from the queue context; */
1484                                 /* or, they may may timeout. */
1485
1486                                 /* Leave if we have exceeded our queuetimeout */
1487                                 if (qe.queuetimeout && ( (time(NULL) - qe.start) >= qe.queuetimeout) ) {
1488                                         res = 0;
1489                                         break;
1490                                 }
1491
1492                                 /* Make a position announcement, if enabled */
1493                                 if (qe.parent->announcefrequency && !ringing)
1494                                         say_position(&qe);
1495
1496                                 /* Try calling all queue members for 'timeout' seconds */
1497                                 res = try_calling(&qe, options, announceoverride, url, &go_on);
1498                                 if (res) {
1499                                         if (res < 0) {
1500                                                 if (!qe.handled)
1501                                                         ast_queue_log(queuename, chan->uniqueid, "NONE", "ABANDON", "%d|%d|%ld", qe.pos, qe.opos, (long)time(NULL) - qe.start);
1502                                         } else if (res > 0)
1503                                                 ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHKEY", "%c|%d", res, qe.pos);
1504                                         break;
1505                                 }
1506
1507                                 /* Leave if we have exceeded our queuetimeout */
1508                                 if (qe.queuetimeout && ( (time(NULL) - qe.start) >= qe.queuetimeout) ) {
1509                                         res = 0;
1510                                         break;
1511                                 }
1512
1513                                 /* OK, we didn't get anybody; wait for 'retry' seconds; may get a digit to exit with */
1514                                 res = wait_a_bit(&qe);
1515                                 if (res < 0) {
1516                                         ast_queue_log(queuename, chan->uniqueid, "NONE", "ABANDON", "%d|%d|%ld", qe.pos, qe.opos, (long)time(NULL) - qe.start);
1517                                         if (option_verbose > 2) {
1518                                                 ast_verbose(VERBOSE_PREFIX_3 "User disconnected when they almost made it\n");
1519                                                 res = -1;
1520                                         }
1521                                         break;
1522                                 }
1523                                 if (res && valid_exit(&qe, res)) {
1524                                         ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHKEY", "%c|%d", res, qe.pos);
1525                                         break;
1526                                 }
1527                                 /* exit after 'timeout' cycle if 'n' option enabled */
1528                                 if (go_on) {
1529                                         if (option_verbose > 2) {
1530                                                 ast_verbose(VERBOSE_PREFIX_3 "Exiting on time-out cycle\n");
1531                                                 res = -1;
1532                                         }
1533                                         ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHTIMEOUT", "%d", qe.pos);
1534                                         res = 0;
1535                                         break;
1536                                 }
1537
1538                         }
1539                 }
1540                 /* Don't allow return code > 0 */
1541                 if (res > 0 && res != AST_PBX_KEEPALIVE) {
1542                         res = 0;        
1543                         if (ringing) {
1544                                 ast_indicate(chan, -1);
1545                         } else {
1546                                 ast_moh_stop(chan);
1547                         }                       
1548                         ast_stopstream(chan);
1549                 }
1550                 leave_queue(&qe);
1551         } else {
1552                 ast_log(LOG_WARNING, "Unable to join queue '%s'\n", queuename);
1553                 res =  0;
1554         }
1555         LOCAL_USER_REMOVE(u);
1556         return res;
1557 }
1558
1559 static void reload_queues(void)
1560 {
1561         struct ast_call_queue *q, *ql, *qn;
1562         struct ast_config *cfg;
1563         char *cat, *tmp;
1564         struct ast_variable *var;
1565         struct member *prev, *cur;
1566         int new;
1567         cfg = ast_load("queues.conf");
1568         if (!cfg) {
1569                 ast_log(LOG_NOTICE, "No call queueing config file, so no call queues\n");
1570                 return;
1571         }
1572         ast_mutex_lock(&qlock);
1573         /* Mark all queues as dead for the moment */
1574         q = queues;
1575         while(q) {
1576                 q->dead = 1;
1577                 q = q->next;
1578         }
1579         /* Chug through config file */
1580         cat = ast_category_browse(cfg, NULL);
1581         while(cat) {
1582                 if (strcasecmp(cat, "general")) {
1583                         /* Look for an existing one */
1584                         q = queues;
1585                         while(q) {
1586                                 if (!strcmp(q->name, cat))
1587                                         break;
1588                                 q = q->next;
1589                         }
1590                         if (!q) {
1591                                 /* Make one then */
1592                                 q = malloc(sizeof(struct ast_call_queue));
1593                                 if (q) {
1594                                         /* Initialize it */
1595                                         memset(q, 0, sizeof(struct ast_call_queue));
1596                                         ast_mutex_init(&q->lock);
1597                                         strncpy(q->name, cat, sizeof(q->name));
1598                                         new = 1;
1599                                 } else new = 0;
1600                         } else
1601                                         new = 0;
1602                         if (q) {
1603                                 if (!new) 
1604                                         ast_mutex_lock(&q->lock);
1605                                 /* Re-initialize the queue */
1606                                 q->dead = 0;
1607                                 q->retry = 0;
1608                                 q->timeout = -1;
1609                                 q->maxlen = 0;
1610                                 q->announcefrequency = 0;
1611                                 q->announceholdtime = 0;
1612                                 q->holdtime = 0;
1613                                 q->callscompleted = 0;
1614                                 q->callsabandoned = 0;
1615                                 q->callscompletedinsl = 0;
1616                                 q->servicelevel = 0;
1617                                 free_members(q, 0);
1618                                 strcpy(q->moh, "");
1619                                 strcpy(q->announce, "");
1620                                 strcpy(q->context, "");
1621                                 strcpy(q->monfmt, "");
1622                                 strcpy(q->sound_next, "queue-youarenext");
1623                                 strcpy(q->sound_thereare, "queue-thereare");
1624                                 strcpy(q->sound_calls, "queue-callswaiting");
1625                                 strcpy(q->sound_holdtime, "queue-holdtime");
1626                                 strcpy(q->sound_minutes, "queue-minutes");
1627                                 strcpy(q->sound_thanks, "queue-thankyou");
1628                                 prev = q->members;
1629                                 if (prev) {
1630                                         /* find the end of any dynamic members */
1631                                         while(prev->next)
1632                                                 prev = prev->next;
1633                                 }
1634                                 var = ast_variable_browse(cfg, cat);
1635                                 while(var) {
1636                                         if (!strcasecmp(var->name, "member")) {
1637                                                 /* Add a new member */
1638                                                 cur = malloc(sizeof(struct member));
1639                                                 if (cur) {
1640                                                         memset(cur, 0, sizeof(struct member));
1641                                                         strncpy(cur->tech, var->value, sizeof(cur->tech) - 1);
1642                                                         if ((tmp = strchr(cur->tech, ','))) {
1643                                                                 *tmp = '\0';
1644                                                                 tmp++;
1645                                                                 cur->penalty = atoi(tmp);
1646                                                                 if (cur->penalty < 0)
1647                                                                         cur->penalty = 0;
1648                                                         }
1649                                                         if ((tmp = strchr(cur->tech, '/')))
1650                                                                 *tmp = '\0';
1651                                                         if ((tmp = strchr(var->value, '/'))) {
1652                                                                 tmp++;
1653                                                                 strncpy(cur->loc, tmp, sizeof(cur->loc) - 1);
1654                                                                 if ((tmp = strchr(cur->loc, ',')))
1655                                                                         *tmp = '\0';
1656                                                         } else
1657                                                                 ast_log(LOG_WARNING, "No location at line %d of queue.conf\n", var->lineno);
1658                                                         if (prev)
1659                                                                 prev->next = cur;
1660                                                         else
1661                                                                 q->members = cur;
1662                                                         prev = cur;
1663                                                 }
1664                                         } else if (!strcasecmp(var->name, "music")) {
1665                                                 strncpy(q->moh, var->value, sizeof(q->moh) - 1);
1666                                         } else if (!strcasecmp(var->name, "announce")) {
1667                                                 strncpy(q->announce, var->value, sizeof(q->announce) - 1);
1668                                         } else if (!strcasecmp(var->name, "context")) {
1669                                                 strncpy(q->context, var->value, sizeof(q->context) - 1);
1670                                         } else if (!strcasecmp(var->name, "timeout")) {
1671                                                 q->timeout = atoi(var->value);
1672                                         } else if (!strcasecmp(var->name, "monitor-join")) {
1673                                                 q->monjoin = ast_true(var->value);
1674                                         } else if (!strcasecmp(var->name, "monitor-format")) {
1675                                                 strncpy(q->monfmt, var->value, sizeof(q->monfmt) - 1);
1676                                         } else if (!strcasecmp(var->name, "queue-youarenext")) {
1677                                                 strncpy(q->sound_next, var->value, sizeof(q->sound_next) - 1);
1678                                         } else if (!strcasecmp(var->name, "queue-thereare")) {
1679                                                 strncpy(q->sound_thereare, var->value, sizeof(q->sound_thereare) - 1);
1680                                         } else if (!strcasecmp(var->name, "queue-callswaiting")) {
1681                                                 strncpy(q->sound_calls, var->value, sizeof(q->sound_calls) - 1);
1682                                         } else if (!strcasecmp(var->name, "queue-holdtime")) {
1683                                                 strncpy(q->sound_holdtime, var->value, sizeof(q->sound_holdtime) - 1);
1684                                         } else if (!strcasecmp(var->name, "queue-minutes")) {
1685                                                 strncpy(q->sound_minutes, var->value, sizeof(q->sound_minutes) - 1);
1686                                         } else if (!strcasecmp(var->name, "queue-thankyou")) {
1687                                                 strncpy(q->sound_thanks, var->value, sizeof(q->sound_thanks) - 1);
1688                                         } else if (!strcasecmp(var->name, "announce-frequency")) {
1689                                                 q->announcefrequency = atoi(var->value);
1690                                         } else if (!strcasecmp(var->name, "announce-holdtime")) {
1691                                                 q->announceholdtime = (!strcasecmp(var->value,"once")) ? 1 : ast_true(var->value);
1692                                         } else if (!strcasecmp(var->name, "retry")) {
1693                                                 q->retry = atoi(var->value);
1694                                         } else if (!strcasecmp(var->name, "maxlen")) {
1695                                                 q->maxlen = atoi(var->value);
1696                                         } else if (!strcasecmp(var->name, "servicelevel")) {
1697                                                 q->servicelevel= atoi(var->value);
1698                                         } else if (!strcasecmp(var->name, "strategy")) {
1699                                                 q->strategy = strat2int(var->value);
1700                                                 if (q->strategy < 0) {
1701                                                         ast_log(LOG_WARNING, "'%s' isn't a valid strategy, using ringall instead\n", var->value);
1702                                                         q->strategy = 0;
1703                                                 }
1704                                         } else {
1705                                                 ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queue.conf\n", cat, var->name, var->lineno);
1706                                         }
1707                                         var = var->next;
1708                                 }
1709                                 if (q->retry < 1)
1710                                         q->retry = DEFAULT_RETRY;
1711                                 if (q->timeout < 0)
1712                                         q->timeout = DEFAULT_TIMEOUT;
1713                                 if (q->maxlen < 0)
1714                                         q->maxlen = 0;
1715                                 if (!new) 
1716                                         ast_mutex_unlock(&q->lock);
1717                                 if (new) {
1718                                         q->next = queues;
1719                                         queues = q;
1720                                 }
1721                         }
1722                 }
1723                 cat = ast_category_browse(cfg, cat);
1724         }
1725         ast_destroy(cfg);
1726         q = queues;
1727         ql = NULL;
1728         while(q) {
1729                 qn = q->next;
1730                 if (q->dead) {
1731                         if (ql)
1732                                 ql->next = q->next;
1733                         else
1734                                 queues = q->next;
1735                         if (!q->count) {
1736                                 free(q);
1737                         } else
1738                                 ast_log(LOG_WARNING, "XXX Leaking a litttle memory :( XXX\n");
1739                 } else
1740                         ql = q;
1741                 q = qn;
1742         }
1743         ast_mutex_unlock(&qlock);
1744 }
1745
1746 static int __queues_show(int fd, int argc, char **argv, int queue_show)
1747 {
1748         struct ast_call_queue *q;
1749         struct queue_ent *qe;
1750         struct member *mem;
1751         int pos;
1752         time_t now;
1753         char max[80];
1754         char calls[80];
1755         float sl = 0;
1756
1757         time(&now);
1758         if ((!queue_show && argc != 2) || (queue_show && argc != 3))
1759                 return RESULT_SHOWUSAGE;
1760         ast_mutex_lock(&qlock);
1761         q = queues;
1762         if (!q) {       
1763                 ast_mutex_unlock(&qlock);
1764                 if (queue_show)
1765                         ast_cli(fd, "No such queue: %s.\n",argv[2]);
1766                 else
1767                         ast_cli(fd, "No queues.\n");
1768                 return RESULT_SUCCESS;
1769         }
1770         while(q) {
1771                 ast_mutex_lock(&q->lock);
1772                 if (queue_show) {
1773                         if (strcasecmp(q->name, argv[2]) != 0) {
1774                                 ast_mutex_unlock(&q->lock);
1775                                 q = q->next;
1776                                 if (!q) {
1777                                         ast_cli(fd, "No such queue: %s.\n",argv[2]);
1778                                         break;
1779                                 }
1780                                 continue;
1781                         }
1782                 }
1783                 if (q->maxlen)
1784                         snprintf(max, sizeof(max), "%d", q->maxlen);
1785                 else
1786                         strcpy(max, "unlimited");
1787                 sl = 0;
1788                 if(q->callscompleted > 0)
1789                         sl = 100*((float)q->callscompletedinsl/(float)q->callscompleted);
1790                 ast_cli(fd, "%-12.12s has %d calls (max %s) in '%s' strategy (%ds holdtime), C:%d, A:%d, SL:%2.1f%% within %ds\n",
1791                         q->name, q->count, max, int2strat(q->strategy), q->holdtime, q->callscompleted, q->callsabandoned,sl,q->servicelevel);
1792                 if (q->members) {
1793                         ast_cli(fd, "   Members: \n");
1794                         for (mem = q->members; mem; mem = mem->next) {
1795                                 if (mem->penalty)
1796                                         snprintf(max, sizeof(max) - 20, " with penalty %d", mem->penalty);
1797                                 else
1798                                         strcpy(max, "");
1799                                 if (mem->dynamic)
1800                                         strcat(max, " (dynamic)");
1801                                 if (mem->calls) {
1802                                         snprintf(calls, sizeof(calls), " has taken %d calls (last was %ld secs ago)",
1803                                                         mem->calls, (long)(time(NULL) - mem->lastcall));
1804                                 } else
1805                                         strcpy(calls, " has taken no calls yet");
1806                                 ast_cli(fd, "      %s/%s%s%s\n", mem->tech, mem->loc, max, calls);
1807                         }
1808                 } else
1809                         ast_cli(fd, "   No Members\n");
1810                 if (q->head) {
1811                         pos = 1;
1812                         ast_cli(fd, "   Callers: \n");
1813                         for (qe = q->head; qe; qe = qe->next) 
1814                                 ast_cli(fd, "      %d. %s (wait: %ld:%2.2ld)\n", pos++, qe->chan->name,
1815                                                                 (long)(now - qe->start) / 60, (long)(now - qe->start) % 60);
1816                 } else
1817                         ast_cli(fd, "   No Callers\n");
1818                 ast_cli(fd, "\n");
1819                 ast_mutex_unlock(&q->lock);
1820                 q = q->next;
1821                 if (queue_show)
1822                         break;
1823         }
1824         ast_mutex_unlock(&qlock);
1825         return RESULT_SUCCESS;
1826 }
1827
1828 static int queues_show(int fd, int argc, char **argv)
1829 {
1830         return __queues_show(fd, argc, argv, 0);
1831 }
1832
1833 static int queue_show(int fd, int argc, char **argv)
1834 {
1835         return __queues_show(fd, argc, argv, 1);
1836 }
1837
1838 static char *complete_queue(char *line, char *word, int pos, int state)
1839 {
1840         struct ast_call_queue *q;
1841         int which=0;
1842         
1843         ast_mutex_lock(&qlock);
1844         q = queues;
1845         while(q) {
1846                 if (!strncasecmp(word, q->name, strlen(word))) {
1847                         if (++which > state)
1848                                 break;
1849                 }
1850                 q = q->next;
1851         }
1852         ast_mutex_unlock(&qlock);
1853         return q ? strdup(q->name) : NULL;
1854 }
1855
1856 /* JDG: callback to display queues status in manager */
1857 static int manager_queues_show( struct mansession *s, struct message *m )
1858 {
1859         char *a[] = { "show", "queues" };
1860         return queues_show( s->fd, 2, a );
1861 } /* /JDG */
1862
1863
1864 /* Dump queue status */
1865 static int manager_queues_status( struct mansession *s, struct message *m )
1866 {
1867         time_t now;
1868         int pos;
1869         char *id = astman_get_header(m,"ActionID");
1870         char idText[256] = "";
1871         struct ast_call_queue *q;
1872         struct queue_ent *qe;
1873         float sl = 0;
1874         struct member *mem;
1875         astman_send_ack(s, m, "Queue status will follow");
1876         time(&now);
1877         ast_mutex_lock(&qlock);
1878         q = queues;
1879         if (id && !ast_strlen_zero(id)) {
1880                 snprintf(idText,256,"ActionID: %s\r\n",id);
1881         }
1882         while(q) {
1883                 ast_mutex_lock(&q->lock);
1884
1885                 /* List queue properties */
1886                 if(q->callscompleted > 0)
1887                         sl = 100*((float)q->callscompletedinsl/(float)q->callscompleted);
1888                 ast_cli(s->fd, "Event: QueueParams\r\n"
1889                                         "Queue: %s\r\n"
1890                                         "Max: %d\r\n"
1891                                         "Calls: %d\r\n"
1892                                         "Holdtime: %d\r\n"
1893                                         "Completed: %d\r\n"
1894                                         "Abandoned: %d\r\n"
1895                                         "ServiceLevel: %d\r\n"
1896                                         "ServicelevelPerf: %2.1f\r\n"
1897                                         "%s"
1898                                         "\r\n",
1899                                                 q->name, q->maxlen, q->count, q->holdtime, q->callscompleted,
1900                                                 q->callsabandoned, q->servicelevel, sl, idText);
1901
1902                 /* List Queue Members */
1903                 for (mem = q->members; mem; mem = mem->next) 
1904                         ast_cli(s->fd, "Event: QueueMember\r\n"
1905                                 "Queue: %s\r\n"
1906                                 "Location: %s/%s\r\n"
1907                                 "Membership: %s\r\n"
1908                                 "Penalty: %d\r\n"
1909                                 "CallsTaken: %d\r\n"
1910                                 "LastCall: %ld\r\n"
1911                                 "%s"
1912                                 "\r\n",
1913                                         q->name, mem->tech, mem->loc, mem->dynamic ? "dynamic" : "static",
1914                                         mem->penalty, mem->calls, mem->lastcall, idText);
1915
1916                 /* List Queue Entries */
1917
1918                 pos = 1;
1919                 for (qe = q->head; qe; qe = qe->next) 
1920                         ast_cli(s->fd, "Event: QueueEntry\r\n"
1921                                 "Queue: %s\r\n"
1922                                 "Position: %d\r\n"
1923                                 "Channel: %s\r\n"
1924                                 "CallerID: %s\r\n"
1925                                 "Wait: %ld\r\n"
1926                                 "%s"
1927                                 "\r\n", 
1928                                         q->name, pos++, qe->chan->name, (qe->chan->callerid ? qe->chan->callerid : ""), (long)(now - qe->start), idText);
1929                 ast_mutex_unlock(&q->lock);
1930                 q = q->next;
1931         }
1932         ast_mutex_unlock(&qlock);
1933         return RESULT_SUCCESS;
1934 }
1935
1936 static char show_queues_usage[] = 
1937 "Usage: show queues\n"
1938 "       Provides summary information on call queues.\n";
1939
1940 static struct ast_cli_entry cli_show_queues = {
1941         { "show", "queues", NULL }, queues_show, 
1942         "Show status of queues", show_queues_usage, NULL };
1943
1944 static char show_queue_usage[] = 
1945 "Usage: show queue\n"
1946 "       Provides summary information on a specified queue.\n";
1947
1948 static struct ast_cli_entry cli_show_queue = {
1949         { "show", "queue", NULL }, queue_show, 
1950         "Show status of a specified queue", show_queue_usage, complete_queue };
1951
1952 int unload_module(void)
1953 {
1954         STANDARD_HANGUP_LOCALUSERS;
1955         ast_cli_unregister(&cli_show_queue);
1956         ast_cli_unregister(&cli_show_queues);
1957         ast_manager_unregister( "Queues" );
1958         ast_manager_unregister( "QueueStatus" );
1959         ast_unregister_application(app_aqm);
1960         ast_unregister_application(app_rqm);
1961         return ast_unregister_application(app);
1962 }
1963
1964 int load_module(void)
1965 {
1966         int res;
1967         res = ast_register_application(app, queue_exec, synopsis, descrip);
1968         if (!res) {
1969                 ast_cli_register(&cli_show_queue);
1970                 ast_cli_register(&cli_show_queues);
1971                 ast_manager_register( "Queues", 0, manager_queues_show, "Queues" );
1972                 ast_manager_register( "QueueStatus", 0, manager_queues_status, "Queue Status" );
1973
1974                 // [PHM 06/26/03]
1975                 ast_register_application(app_aqm, aqm_exec, app_aqm_synopsis, app_aqm_descrip) ;
1976                 ast_register_application(app_rqm, rqm_exec, app_rqm_synopsis, app_rqm_descrip) ;
1977         }
1978         reload_queues();
1979         return res;
1980 }
1981
1982
1983 int reload(void)
1984 {
1985         reload_queues();
1986         return 0;
1987 }
1988
1989 char *description(void)
1990 {
1991         return tdesc;
1992 }
1993
1994 int usecount(void)
1995 {
1996         int res;
1997         STANDARD_USECOUNT(res);
1998         return res;
1999 }
2000
2001 char *key()
2002 {
2003         return ASTERISK_GPL_KEY;
2004 }