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