Additional queue optimization (bug #3093, with mods)
[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-2004, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
9  *
10  * 2004-11-25: Persistent Dynamic Members added by:
11  *             NetNation Communications (www.netnation.com)
12  *             Kevin Lindsay <kevinl@netnation.com>
13  * 
14  *             Each dynamic agent in each queue is now stored in the astdb.
15  *             When asterisk is restarted, each agent will be automatically
16  *             readded into their recorded queues. This feature can be
17  *             configured with the 'peristent_members=<1|0>' KVP under the
18  *             '[general]' group in queues.conf. The default is on.
19  * 
20  * 2004-06-04: Priorities in queues added by inAccess Networks (work funded by Hellas On Line (HOL) www.hol.gr).
21  *
22  * These features added by David C. Troy <dave@toad.net>:
23  *    - Per-queue holdtime calculation
24  *    - Estimated holdtime announcement
25  *    - Position announcement
26  *    - Abandoned/completed call counters
27  *    - Failout timer passed as optional app parameter
28  *    - Optional monitoring of calls, started when call is answered
29  *
30  * Patch Version 1.07 2003-12-24 01
31  *
32  * Added servicelevel statistic by Michiel Betel <michiel@betel.nl>
33  * Added Priority jumping code for adding and removing queue members by Jonathan Stanton <asterisk@doilooklikeicare.com>
34  *
35  * Fixed to work with CVS as of 2004-02-25 and released as 1.07a
36  * by Matthew Enger <m.enger@xi.com.au>
37  *
38  * This program is free software, distributed under the terms of
39  * the GNU General Public License
40  */
41
42 #include <asterisk/lock.h>
43 #include <asterisk/file.h>
44 #include <asterisk/logger.h>
45 #include <asterisk/channel.h>
46 #include <asterisk/pbx.h>
47 #include <asterisk/options.h>
48 #include <asterisk/module.h>
49 #include <asterisk/translate.h>
50 #include <asterisk/say.h>
51 #include <asterisk/features.h>
52 #include <asterisk/musiconhold.h>
53 #include <asterisk/cli.h>
54 #include <asterisk/manager.h>
55 #include <asterisk/config.h>
56 #include <asterisk/monitor.h>
57 #include <asterisk/utils.h>
58 #include <asterisk/causes.h>
59 #include <asterisk/astdb.h>
60 #include <stdlib.h>
61 #include <errno.h>
62 #include <unistd.h>
63 #include <string.h>
64 #include <stdlib.h>
65 #include <stdio.h>
66 #include <sys/time.h>
67 #include <sys/signal.h>
68 #include <netinet/in.h>
69
70 #include "../astconf.h"
71
72 #define QUEUE_STRATEGY_RINGALL          0
73 #define QUEUE_STRATEGY_ROUNDROBIN       1
74 #define QUEUE_STRATEGY_LEASTRECENT      2
75 #define QUEUE_STRATEGY_FEWESTCALLS      3
76 #define QUEUE_STRATEGY_RANDOM           4
77 #define QUEUE_STRATEGY_RRMEMORY         5
78
79 static struct strategy {
80         int strategy;
81         char *name;
82 } strategies[] = {
83         { QUEUE_STRATEGY_RINGALL, "ringall" },
84         { QUEUE_STRATEGY_ROUNDROBIN, "roundrobin" },
85         { QUEUE_STRATEGY_LEASTRECENT, "leastrecent" },
86         { QUEUE_STRATEGY_FEWESTCALLS, "fewestcalls" },
87         { QUEUE_STRATEGY_RANDOM, "random" },
88         { QUEUE_STRATEGY_RRMEMORY, "rrmemory" },
89 };
90
91 #define DEFAULT_RETRY           5
92 #define DEFAULT_TIMEOUT         15
93 #define RECHECK                         1               /* Recheck every second to see we we're at the top yet */
94
95 #define RES_OKAY        0                       /* Action completed */
96 #define RES_EXISTS      (-1)            /* Entry already exists */
97 #define RES_OUTOFMEMORY (-2)    /* Out of memory */
98 #define RES_NOSUCHQUEUE (-3)    /* No such queue */
99
100 static char *tdesc = "True Call Queueing";
101
102 static char *app = "Queue";
103
104 static char *synopsis = "Queue a call for a call queue";
105
106 static char *descrip =
107 "  Queue(queuename[|options[|URL][|announceoverride][|timeout]]):\n"
108 "Queues an incoming call in a particular call queue as defined in queues.conf.\n"
109 "  This application returns -1 if the originating channel hangs up, or if the\n"
110 "call is bridged and  either of the parties in the bridge terminate the call.\n"
111 "Returns 0 if the queue is full, nonexistant, or has no members.\n"
112 "The option string may contain zero or more of the following characters:\n"
113 "      't' -- allow the called user transfer the calling user\n"
114 "      'T' -- to allow the calling user to transfer the call.\n"
115 "      'd' -- data-quality (modem) call (minimum delay).\n"
116 "      'h' -- allow callee to hang up by hitting *.\n"
117 "      'H' -- allow caller to hang up by hitting *.\n"
118 "      'n' -- no retries on the timeout; will exit this application and go to the next step.\n"
119 "      'r' -- ring instead of playing MOH\n"
120 "  In addition to transferring the call, a call may be parked and then picked\n"
121 "up by another user.\n"
122 "  The optional URL will be sent to the called party if the channel supports\n"
123 "it.\n"
124 "  The timeout will cause the queue to fail out after a specified number of\n"
125 "seconds, checked between each queues.conf 'timeout' and 'retry' cycle.\n";
126
127 /* PHM 06/26/03 */
128 static char *app_aqm = "AddQueueMember" ;
129 static char *app_aqm_synopsis = "Dynamically adds queue members" ;
130 static char *app_aqm_descrip =
131 "   AddQueueMember(queuename[|interface[|penalty]]):\n"
132 "Dynamically adds interface to an existing queue.\n"
133 "If the interface is already in the queue and there exists an n+101 priority\n"
134 "then it will then jump to this priority.  Otherwise it will return an error\n"
135 "Returns -1 if there is an error.\n"
136 "Example: AddQueueMember(techsupport|SIP/3000)\n"
137 "";
138
139 static char *app_rqm = "RemoveQueueMember" ;
140 static char *app_rqm_synopsis = "Dynamically removes queue members" ;
141 static char *app_rqm_descrip =
142 "   RemoveQueueMember(queuename[|interface]):\n"
143 "Dynamically removes interface to an existing queue\n"
144 "If the interface is NOT in the queue and there exists an n+101 priority\n"
145 "then it will then jump to this priority.  Otherwise it will return an error\n"
146 "Returns -1 if there is an error.\n"
147 "Example: RemoveQueueMember(techsupport|SIP/3000)\n"
148 "";
149
150 /* Persistent Members astdb family */
151 static const char *pm_family = "/Queue/PersistentMembers";
152 /* The maximum lengh of each persistent member queue database entry */
153 #define PM_MAX_LEN 2048
154 /* queues.conf [general] option */
155 static int queue_persistent_members = 0;
156
157 /* We define a customer "local user" structure because we
158    use it not only for keeping track of what is in use but
159    also for keeping track of who we're dialing. */
160
161 struct localuser {
162         struct ast_channel *chan;
163         char interface[256];
164         int stillgoing;
165         int metric;
166         int oldstatus;
167         int allowredirect_in;
168         int allowredirect_out;
169         int ringbackonly;
170         int musiconhold;
171         int dataquality;
172         int allowdisconnect_in;
173         int allowdisconnect_out;
174         time_t lastcall;
175         struct member *member;
176         struct localuser *next;
177 };
178
179 LOCAL_USER_DECL;
180
181 struct queue_ent {
182         struct ast_call_queue *parent;  /* What queue is our parent */
183         char moh[80];                   /* Name of musiconhold to be used */
184         char announce[80];              /* Announcement to play for member when call is answered */
185         char context[80];               /* Context when user exits queue */
186         int pos;                                        /* Where we are in the queue */
187         int prio;                                       /* Our priority */
188         int last_pos_said;              /* Last position we told the user */
189         time_t last_pos;                /* Last time we told the user their position */
190         int opos;                       /* Where we started in the queue */
191         int handled;                    /* Whether our call was handled */
192         time_t start;                   /* When we started holding */
193         time_t expire;                  /* When this entry should expire (time out of queue) */
194         struct ast_channel *chan;       /* Our channel */
195         struct queue_ent *next;         /* The next queue entry */
196 };
197
198 struct member {
199         char interface[80];                     /* Technology/Location */
200         int penalty;                            /* Are we a last resort? */
201         int calls;                                      /* Number of calls serviced by this member */
202         int dynamic;                            /* Are we dynamically added? */
203         int status;                                     /* Status of queue member */
204         time_t lastcall;                        /* When last successful call was hungup */
205         struct member *next;            /* Next member */
206 };
207
208 struct ast_call_queue {
209         ast_mutex_t     lock;   
210         char name[80];                  /* Name of the queue */
211         char moh[80];                   /* Name of musiconhold to be used */
212         char announce[80];              /* Announcement to play when call is answered */
213         char context[80];               /* Context for this queue */
214         int strategy;                   /* Queueing strategy */
215         int announcefrequency;          /* How often to announce their position */
216         int roundingseconds;            /* How many seconds do we round to? */
217         int announceholdtime;           /* When to announce holdtime: 0 = never, -1 = every announcement, 1 = only once */
218         int holdtime;                   /* Current avg holdtime for this queue, based on recursive boxcar filter */
219         int callscompleted;             /* Number of queue calls completed */
220         int callsabandoned;             /* Number of queue calls abandoned */
221         int servicelevel;               /* seconds setting for servicelevel*/
222         int callscompletedinsl;         /* Number of queue calls answererd with servicelevel*/
223         char monfmt[8];                 /* Format to use when recording calls */
224         int monjoin;                    /* Should we join the two files when we are done with the call */
225         char sound_next[80];            /* Sound file: "Your call is now first in line" (def. queue-youarenext) */
226         char sound_thereare[80];        /* Sound file: "There are currently" (def. queue-thereare) */
227         char sound_calls[80];           /* Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting)*/
228         char sound_holdtime[80];        /* Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
229         char sound_minutes[80];         /* Sound file: "minutes." (def. queue-minutes) */
230         char sound_lessthan[80];        /* Sound file: "less-than" (def. queue-lessthan) */
231         char sound_seconds[80];         /* Sound file: "seconds." (def. queue-seconds) */
232         char sound_thanks[80];          /* Sound file: "Thank you for your patience." (def. queue-thankyou) */
233         char sound_reporthold[80];      /* Sound file: "Hold time" (def. queue-reporthold) */
234
235         int count;                      /* How many entries are in the queue */
236         int maxlen;                     /* Max number of entries in queue */
237         int wrapuptime;         /* Wrapup Time */
238
239         int dead;                       /* Whether this queue is dead or not */
240         int retry;                      /* Retry calling everyone after this amount of time */
241         int timeout;                    /* How long to wait for an answer */
242         
243         /* Queue strategy things */
244         
245         int rrpos;                      /* Round Robin - position */
246         int wrapped;                    /* Round Robin - wrapped around? */
247         int joinempty;                  /* Do we care if the queue has no members? */
248         int eventwhencalled;                    /* Generate an event when the agent is called (before pickup) */
249         int leavewhenempty;             /* If all agents leave the queue, remove callers from the queue */
250         int reportholdtime;             /* Should we report caller hold time to member? */
251         int memberdelay;                /* Seconds to delay connecting member to caller */
252
253         struct member *members;         /* Member channels to be tried */
254         struct queue_ent *head;         /* Start of the actual queue */
255         struct ast_call_queue *next;    /* Next call queue */
256 };
257
258 static struct ast_call_queue *queues = NULL;
259 AST_MUTEX_DEFINE_STATIC(qlock);
260
261 static char *int2strat(int strategy)
262 {
263         int x;
264         for (x=0;x<sizeof(strategies) / sizeof(strategies[0]);x++) {
265                 if (strategy == strategies[x].strategy)
266                         return strategies[x].name;
267         }
268         return "<unknown>";
269 }
270
271 static int strat2int(char *strategy)
272 {
273         int x;
274         for (x=0;x<sizeof(strategies) / sizeof(strategies[0]);x++) {
275                 if (!strcasecmp(strategy, strategies[x].name))
276                         return strategies[x].strategy;
277         }
278         return -1;
279 }
280
281 /* Insert the 'new' entry after the 'prev' entry of queue 'q' */
282 static inline void insert_entry(struct ast_call_queue *q, 
283                                         struct queue_ent *prev, struct queue_ent *new, int *pos)
284 {
285         struct queue_ent *cur;
286
287         if (!q || !new)
288                 return;
289         if (prev) {
290                 cur = prev->next;
291                 prev->next = new;
292         } else {
293                 cur = q->head;
294                 q->head = new;
295         }
296         new->next = cur;
297         new->parent = q;
298         new->pos = ++(*pos);
299         new->opos = *pos;
300 }
301
302 static int has_no_members(struct ast_call_queue *q)
303 {
304         struct member *member;
305         int empty = 1;
306         member = q->members;
307         while(empty && member) {
308                 switch(member->status) {
309                 case AST_DEVICE_UNAVAILABLE:
310                 case AST_DEVICE_INVALID:
311                         /* Not logged on, etc */
312                         break;
313                 default:
314                         /* Not empty */
315                         empty = 0;
316                 }
317                 member = member->next;
318         }
319         return empty;
320 }
321
322 struct statechange {
323         int state;
324         char dev[0];
325 };
326
327 static void *changethread(void *data)
328 {
329         struct ast_call_queue *q;
330         struct statechange *sc = data;
331         struct member *cur;
332         char *loc;
333         loc = strchr(sc->dev, '/');
334         if (loc) {
335                 *loc = '\0';
336                 loc++;
337         } else {
338                 ast_log(LOG_WARNING, "Can't change device with no technology!\n");
339                 free(sc);
340                 return NULL;
341         }
342         if (option_debug)
343                 ast_log(LOG_DEBUG, "Device '%s/%s' changed to state '%d'\n", sc->dev, loc, sc->state);
344         ast_mutex_lock(&qlock);
345         for (q = queues; q; q = q->next) {
346                 ast_mutex_lock(&q->lock);
347                 cur = q->members;
348                 while(cur) {
349                         if (!strcasecmp(sc->dev, cur->interface)) {
350                                 if (cur->status != sc->state) {
351                                         cur->status = sc->state;
352                                         manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
353                                                 "Queue: %s\r\n"
354                                                 "Location: %s\r\n"
355                                                 "Membership: %s\r\n"
356                                                 "Penalty: %d\r\n"
357                                                 "CallsTaken: %d\r\n"
358                                                 "LastCall: %ld\r\n"
359                                                 "Status: %d\r\n",
360                                         q->name, cur->interface, cur->dynamic ? "dynamic" : "static",
361                                         cur->penalty, cur->calls, cur->lastcall, cur->status);
362                                 }
363                         }
364                         cur = cur->next;
365                 }
366                 ast_mutex_unlock(&q->lock);
367         }
368         ast_mutex_unlock(&qlock);
369         ast_log(LOG_DEBUG, "Device '%s/%s' changed to state '%d'\n", sc->dev, loc, sc->state);
370         free(sc);
371         return NULL;
372 }
373
374 static int statechange_queue(const char *dev, int state, void *ign)
375 {
376         /* Avoid potential for deadlocks by spawning a new thread to handle
377            the event */
378         struct statechange *sc;
379         pthread_t t;
380         pthread_attr_t attr;
381         sc = malloc(sizeof(struct statechange) + strlen(dev) + 1);
382         if (sc) {
383                 sc->state = state;
384                 strcpy(sc->dev, dev);
385                 pthread_attr_init(&attr);
386                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
387                 if (ast_pthread_create(&t, &attr, changethread, sc)) {
388                         ast_log(LOG_WARNING, "Failed to create update thread!\n");
389                         free(sc);
390                 }
391         }
392         return 0;
393 }
394
395 static int join_queue(char *queuename, struct queue_ent *qe)
396 {
397         struct ast_call_queue *q;
398         struct queue_ent *cur, *prev = NULL;
399         int res = -1;
400         int pos = 0;
401         int inserted = 0;
402
403         ast_mutex_lock(&qlock);
404         for (q = queues; q; q = q->next) {
405                 if (!strcasecmp(q->name, queuename)) {
406                         /* This is our one */
407                         ast_mutex_lock(&q->lock);
408                         if ((!has_no_members(q) || q->joinempty) && (!q->maxlen || (q->count < q->maxlen))) {
409                                 /* There's space for us, put us at the right position inside
410                                  * the queue. 
411                                  * Take into account the priority of the calling user */
412                                 inserted = 0;
413                                 prev = NULL;
414                                 cur = q->head;
415                                 while(cur) {
416                                         /* We have higher priority than the current user, enter
417                                          * before him, after all the other users with priority
418                                          * higher or equal to our priority. */
419                                         if ((!inserted) && (qe->prio > cur->prio)) {
420                                                 insert_entry(q, prev, qe, &pos);
421                                                 inserted = 1;
422                                         }
423                                         cur->pos = ++pos;
424                                         prev = cur;
425                                         cur = cur->next;
426                                 }
427                                 /* No luck, join at the end of the queue */
428                                 if (!inserted)
429                                         insert_entry(q, prev, qe, &pos);
430                                 strncpy(qe->moh, q->moh, sizeof(qe->moh) - 1);
431                                 strncpy(qe->announce, q->announce, sizeof(qe->announce) - 1);
432                                 strncpy(qe->context, q->context, sizeof(qe->context) - 1);
433                                 q->count++;
434                                 res = 0;
435                                 manager_event(EVENT_FLAG_CALL, "Join", 
436                                         "Channel: %s\r\nCallerID: %s\r\nCallerIDName: %s\r\nQueue: %s\r\nPosition: %d\r\nCount: %d\r\n",
437                                         qe->chan->name, 
438                                         qe->chan->cid.cid_num ? qe->chan->cid.cid_num : "unknown",
439                                         qe->chan->cid.cid_name ? qe->chan->cid.cid_name : "unknown",
440                                         q->name, qe->pos, q->count );
441 #if 0
442 ast_log(LOG_NOTICE, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, qe->chan->name, qe->pos );
443 #endif
444                         }
445                         ast_mutex_unlock(&q->lock);
446                         break;
447                 }
448         }
449         ast_mutex_unlock(&qlock);
450         return res;
451 }
452
453 static void free_members(struct ast_call_queue *q, int all)
454 {
455         /* Free non-dynamic members */
456         struct member *curm, *next, *prev;
457         curm = q->members;
458         prev = NULL;
459         while(curm) {
460                 next = curm->next;
461                 if (all || !curm->dynamic) {
462                         if (prev)
463                                 prev->next = next;
464                         else
465                                 q->members = next;
466                         free(curm);
467                 } else 
468                         prev = curm;
469                 curm = next;
470         }
471 }
472
473 static void destroy_queue(struct ast_call_queue *q)
474 {
475         struct ast_call_queue *cur, *prev = NULL;
476         ast_mutex_lock(&qlock);
477         for (cur = queues; cur; cur = cur->next) {
478                 if (cur == q) {
479                         if (prev)
480                                 prev->next = cur->next;
481                         else
482                                 queues = cur->next;
483                 } else {
484                         prev = cur;
485                 }
486         }
487         ast_mutex_unlock(&qlock);
488         free_members(q, 1);
489         ast_mutex_destroy(&q->lock);
490         free(q);
491 }
492
493 static int play_file(struct ast_channel *chan, char *filename)
494 {
495         int res;
496
497         ast_stopstream(chan);
498         res = ast_streamfile(chan, filename, chan->language);
499
500         if (!res)
501                 res = ast_waitstream(chan, "");
502         else
503                 res = 0;
504
505         if (res) {
506                 ast_log(LOG_WARNING, "ast_streamfile failed on %s \n", chan->name);
507                 res = 0;
508         }
509         ast_stopstream(chan);
510
511         return res;
512 }
513
514 static int say_position(struct queue_ent *qe)
515 {
516         int res = 0, avgholdmins, avgholdsecs;
517         time_t now;
518
519         /* Check to see if this is ludicrous -- if we just announced position, don't do it again*/
520         time(&now);
521         if ( (now - qe->last_pos) < 15 )
522                 return -1;
523
524         /* If either our position has changed, or we are over the freq timer, say position */
525         if ( (qe->last_pos_said == qe->pos) && ((now - qe->last_pos) < qe->parent->announcefrequency) )
526                 return -1;
527
528         ast_moh_stop(qe->chan);
529         /* Say we're next, if we are */
530         if (qe->pos == 1) {
531                 res += play_file(qe->chan, qe->parent->sound_next);
532                 goto posout;
533         } else {
534                 res += play_file(qe->chan, qe->parent->sound_thereare);
535                 res += ast_say_number(qe->chan, qe->pos, AST_DIGIT_ANY, qe->chan->language, (char *) NULL); /* Needs gender */
536                 res += play_file(qe->chan, qe->parent->sound_calls);
537         }
538         /* Round hold time to nearest minute */
539         avgholdmins = abs(( (qe->parent->holdtime + 30) - (now - qe->start) ) / 60);
540
541         /* If they have specified a rounding then round the seconds as well */
542         if(qe->parent->roundingseconds) {
543                 avgholdsecs = (abs(( (qe->parent->holdtime + 30) - (now - qe->start) )) - 60 * avgholdmins) / qe->parent->roundingseconds;
544                 avgholdsecs*= qe->parent->roundingseconds;
545         } else {
546                 avgholdsecs=0;
547         }
548
549         if (option_verbose > 2)
550                 ast_verbose(VERBOSE_PREFIX_3 "Hold time for %s is %d minutes %d seconds\n", qe->parent->name, avgholdmins, avgholdsecs);
551
552         /* If the hold time is >1 min, if it's enabled, and if it's not
553            supposed to be only once and we have already said it, say it */
554         if ((avgholdmins+avgholdsecs) > 0 && (qe->parent->announceholdtime) && (!(qe->parent->announceholdtime==1 && qe->last_pos)) ) {
555                 res += play_file(qe->chan, qe->parent->sound_holdtime);
556                 if(avgholdmins>0) {
557                         if (avgholdmins < 2) {
558                                 res += play_file(qe->chan, qe->parent->sound_lessthan);
559                                 res += ast_say_number(qe->chan, 2, AST_DIGIT_ANY, qe->chan->language, (char *)NULL);
560                         } else 
561                                 res += ast_say_number(qe->chan, avgholdmins, AST_DIGIT_ANY, qe->chan->language, (char*) NULL);
562                         res += play_file(qe->chan, qe->parent->sound_minutes);
563                 }
564                 if(avgholdsecs>0) {
565                         res += ast_say_number(qe->chan, avgholdsecs, AST_DIGIT_ANY, qe->chan->language, (char*) NULL);
566                         res += play_file(qe->chan, qe->parent->sound_seconds);
567                 }
568
569         }
570
571         posout:
572         /* Set our last_pos indicators */
573         qe->last_pos = now;
574         qe->last_pos_said = qe->pos;
575
576         if (option_verbose > 2)
577                 ast_verbose(VERBOSE_PREFIX_3 "Told %s in %s their queue position (which was %d)\n", qe->chan->name, qe->parent->name, qe->pos);
578         res += play_file(qe->chan, qe->parent->sound_thanks);
579         ast_moh_start(qe->chan, qe->moh);
580
581         return (res>0);
582 }
583
584 static void record_abandoned(struct queue_ent *qe)
585 {
586         ast_mutex_lock(&qe->parent->lock);
587         qe->parent->callsabandoned++;
588         ast_mutex_unlock(&qe->parent->lock);
589 }
590
591 static void recalc_holdtime(struct queue_ent *qe)
592 {
593         int oldvalue, newvalue;
594
595         /* Calculate holdtime using a recursive boxcar filter */
596         /* Thanks to SRT for this contribution */
597         /* 2^2 (4) is the filter coefficient; a higher exponent would give old entries more weight */
598
599         newvalue = time(NULL) - qe->start;
600
601         ast_mutex_lock(&qe->parent->lock);
602         if (newvalue <= qe->parent->servicelevel)
603                 qe->parent->callscompletedinsl++;
604         oldvalue = qe->parent->holdtime;
605         qe->parent->holdtime = (((oldvalue << 2) - oldvalue) + newvalue) >> 2;
606         ast_mutex_unlock(&qe->parent->lock);
607 }
608
609
610 static void leave_queue(struct queue_ent *qe)
611 {
612         struct ast_call_queue *q;
613         struct queue_ent *cur, *prev = NULL;
614         int pos = 0;
615         q = qe->parent;
616         if (!q)
617                 return;
618         ast_mutex_lock(&q->lock);
619
620         prev = NULL;
621         cur = q->head;
622         while(cur) {
623                 if (cur == qe) {
624                         q->count--;
625
626                         /* Take us out of the queue */
627                         manager_event(EVENT_FLAG_CALL, "Leave",
628                                 "Channel: %s\r\nQueue: %s\r\nCount: %d\r\n",
629                                 qe->chan->name, q->name,  q->count);
630 #if 0
631 ast_log(LOG_NOTICE, "Queue '%s' Leave, Channel '%s'\n", q->name, qe->chan->name );
632 #endif
633                         /* Take us out of the queue */
634                         if (prev)
635                                 prev->next = cur->next;
636                         else
637                                 q->head = cur->next;
638                 } else {
639                         /* Renumber the people after us in the queue based on a new count */
640                         cur->pos = ++pos;
641                         prev = cur;
642                 }
643                 cur = cur->next;
644         }
645         ast_mutex_unlock(&q->lock);
646         if (q->dead && !q->count) {     
647                 /* It's dead and nobody is in it, so kill it */
648                 destroy_queue(q);
649         }
650 }
651
652 static void hanguptree(struct localuser *outgoing, struct ast_channel *exception)
653 {
654         /* Hang up a tree of stuff */
655         struct localuser *oo;
656         while(outgoing) {
657                 /* Hangup any existing lines we have open */
658                 if (outgoing->chan && (outgoing->chan != exception))
659                         ast_hangup(outgoing->chan);
660                 oo = outgoing;
661                 outgoing=outgoing->next;
662                 free(oo);
663         }
664 }
665
666 static int update_status(struct ast_call_queue *q, struct member *member, int status)
667 {
668         struct member *cur;
669         /* Since a reload could have taken place, we have to traverse the list to
670                 be sure it's still valid */
671         ast_mutex_lock(&q->lock);
672         cur = q->members;
673         while(cur) {
674                 if (member == cur) {
675                         cur->status = status;
676                         manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
677                                 "Queue: %s\r\n"
678                                 "Location: %s\r\n"
679                                 "Membership: %s\r\n"
680                                 "Penalty: %d\r\n"
681                                 "CallsTaken: %d\r\n"
682                                 "LastCall: %ld\r\n"
683                                 "Status: %d\r\n",
684                                         q->name, cur->interface, cur->dynamic ? "dynamic" : "static",
685                                         cur->penalty, cur->calls, cur->lastcall, cur->status);
686                         break;
687                 }
688                 cur = cur->next;
689         }
690         q->callscompleted++;
691         ast_mutex_unlock(&q->lock);
692         return 0;
693 }
694
695 static int update_dial_status(struct ast_call_queue *q, struct member *member, int status)
696 {
697         if (status == AST_CAUSE_BUSY)
698                 status = AST_DEVICE_BUSY;
699         else if (status == AST_CAUSE_UNREGISTERED)
700                 status = AST_DEVICE_UNAVAILABLE;
701         else if (status == AST_CAUSE_NOSUCHDRIVER)
702                 status = AST_DEVICE_INVALID;
703         else
704                 status = AST_DEVICE_UNKNOWN;
705         return update_status(q, member, status);
706 }
707
708 static int ring_entry(struct queue_ent *qe, struct localuser *tmp)
709 {
710         int res;
711         int status;
712         char tech[256];
713         char *location;
714
715         if (qe->parent->wrapuptime && (time(NULL) - tmp->lastcall < qe->parent->wrapuptime)) {
716                 ast_log(LOG_DEBUG, "Wrapuptime not yet expired for %s\n", tmp->interface);
717                 if (qe->chan->cdr)
718                         ast_cdr_busy(qe->chan->cdr);
719                 tmp->stillgoing = 0;
720                 return 0;
721         }
722         
723         strncpy(tech, tmp->interface, sizeof(tech) - 1);
724         if ((location = strchr(tech, '/')))
725                 *location++ = '\0';
726         else
727                 location = "";
728
729         /* Request the peer */
730         tmp->chan = ast_request(tech, qe->chan->nativeformats, location, &status);
731         if (!tmp->chan) {                       /* If we can't, just go on to the next call */
732 #if 0
733                 ast_log(LOG_NOTICE, "Unable to create channel of type '%s'\n", cur->tech);
734 #endif                  
735                 if (qe->chan->cdr)
736                         ast_cdr_busy(qe->chan->cdr);
737                 tmp->stillgoing = 0;
738                 update_dial_status(qe->parent, tmp->member, status);
739                 return 0;
740         } else if (status != tmp->oldstatus) 
741                 update_dial_status(qe->parent, tmp->member, status);
742         
743         tmp->chan->appl = "AppQueue";
744         tmp->chan->data = "(Outgoing Line)";
745         tmp->chan->whentohangup = 0;
746         if (tmp->chan->cid.cid_num)
747                 free(tmp->chan->cid.cid_num);
748         tmp->chan->cid.cid_num = NULL;
749         if (tmp->chan->cid.cid_name)
750                 free(tmp->chan->cid.cid_name);
751         tmp->chan->cid.cid_name = NULL;
752         if (tmp->chan->cid.cid_ani)
753                 free(tmp->chan->cid.cid_ani);
754         tmp->chan->cid.cid_ani = NULL;
755         if (qe->chan->cid.cid_num)
756                 tmp->chan->cid.cid_num = strdup(qe->chan->cid.cid_num);
757         if (qe->chan->cid.cid_name)
758                 tmp->chan->cid.cid_name = strdup(qe->chan->cid.cid_name);
759         if (qe->chan->cid.cid_ani)
760                 tmp->chan->cid.cid_ani = strdup(qe->chan->cid.cid_ani);
761         /* Presense of ADSI CPE on outgoing channel follows ours */
762         tmp->chan->adsicpe = qe->chan->adsicpe;
763         /* Place the call, but don't wait on the answer */
764         res = ast_call(tmp->chan, location, 0);
765         if (res) {
766                 /* Again, keep going even if there's an error */
767                 if (option_debug)
768                         ast_log(LOG_DEBUG, "ast call on peer returned %d\n", res);
769                 else if (option_verbose > 2)
770                         ast_verbose(VERBOSE_PREFIX_3 "Couldn't call %s\n", tmp->interface);
771                 ast_hangup(tmp->chan);
772                 tmp->chan = NULL;
773                 tmp->stillgoing = 0;
774                 return 0;
775         } else {
776                 if (qe->parent->eventwhencalled) {
777                         manager_event(EVENT_FLAG_AGENT, "AgentCalled",
778                                                 "AgentCalled: %s\r\n"
779                                                 "ChannelCalling: %s\r\n"
780                                                 "CallerID: %s\r\n"
781                                                 "CallerIDName: %s\r\n"
782                                                 "Context: %s\r\n"
783                                                 "Extension: %s\r\n"
784                                                 "Priority: %d\r\n",
785                                                 tmp->interface, qe->chan->name,
786                                                 tmp->chan->cid.cid_num ? tmp->chan->cid.cid_num : "unknown",
787                                                 tmp->chan->cid.cid_name ? tmp->chan->cid.cid_name : "unknown",
788                                                 qe->chan->context, qe->chan->exten, qe->chan->priority);
789                 }
790                 if (option_verbose > 2)
791                         ast_verbose(VERBOSE_PREFIX_3 "Called %s\n", tmp->interface);
792         }
793         return 0;
794 }
795
796 static int ring_one(struct queue_ent *qe, struct localuser *outgoing)
797 {
798         struct localuser *cur;
799         struct localuser *best;
800         int bestmetric=0;
801         do {
802                 best = NULL;
803                 cur = outgoing;
804                 while(cur) {
805                         if (cur->stillgoing &&                                                  /* Not already done */
806                                 !cur->chan &&                                                           /* Isn't already going */
807                                 (!best || (cur->metric < bestmetric))) {        /* We haven't found one yet, or it's better */
808                                         bestmetric = cur->metric;
809                                         best = cur;
810                         }
811                         cur = cur->next;
812                 }
813                 if (best) {
814                         if (!qe->parent->strategy) {
815                                 /* Ring everyone who shares this best metric (for ringall) */
816                                 cur = outgoing;
817                                 while(cur) {
818                                         if (cur->stillgoing && !cur->chan && (cur->metric == bestmetric)) {
819                                                 ast_log(LOG_DEBUG, "(Parallel) Trying '%s' with metric %d\n", cur->interface, cur->metric);
820                                                 ring_entry(qe, cur);
821                                         }
822                                         cur = cur->next;
823                                 }
824                         } else {
825                                 /* Ring just the best channel */
826                                 if (option_debug)
827                                         ast_log(LOG_DEBUG, "Trying '%s' with metric %d\n", best->interface, best->metric);
828                                 ring_entry(qe, best);
829                         }
830                 }
831         } while (best && !best->chan);
832         if (!best) {
833                 if (option_debug)
834                         ast_log(LOG_DEBUG, "Nobody left to try ringing in queue\n");
835                 return 0;
836         }
837         return 1;
838 }
839
840 static int store_next(struct queue_ent *qe, struct localuser *outgoing)
841 {
842         struct localuser *cur;
843         struct localuser *best;
844         int bestmetric=0;
845         best = NULL;
846         cur = outgoing;
847         while(cur) {
848                 if (cur->stillgoing &&                                                  /* Not already done */
849                         !cur->chan &&                                                           /* Isn't already going */
850                         (!best || (cur->metric < bestmetric))) {        /* We haven't found one yet, or it's better */
851                                 bestmetric = cur->metric;
852                                 best = cur;
853                 }
854                 cur = cur->next;
855         }
856         if (best) {
857                 /* Ring just the best channel */
858                 ast_log(LOG_DEBUG, "Next is '%s' with metric %d\n", best->interface, best->metric);
859                 qe->parent->rrpos = best->metric % 1000;
860         } else {
861                 /* Just increment rrpos */
862                 if (!qe->parent->wrapped) {
863                         /* No more channels, start over */
864                         qe->parent->rrpos = 0;
865                 } else {
866                         /* Prioritize next entry */
867                         qe->parent->rrpos++;
868                 }
869         }
870         qe->parent->wrapped = 0;
871         return 0;
872 }
873
874 static int valid_exit(struct queue_ent *qe, char digit)
875 {
876         char tmp[2];
877         if (ast_strlen_zero(qe->context))
878                 return 0;
879         tmp[0] = digit;
880         tmp[1] = '\0';
881         if (ast_exists_extension(qe->chan, qe->context, tmp, 1, qe->chan->cid.cid_num)) {
882                 strncpy(qe->chan->context, qe->context, sizeof(qe->chan->context) - 1);
883                 strncpy(qe->chan->exten, tmp, sizeof(qe->chan->exten) - 1);
884                 qe->chan->priority = 0;
885                 return 1;
886         }
887         return 0;
888 }
889
890 #define AST_MAX_WATCHERS 256
891
892 static struct localuser *wait_for_answer(struct queue_ent *qe, struct localuser *outgoing, int *to, int *allowredir_in, int *allowredir_out, int *allowdisconnect_in, int *allowdisconnect_out, char *digit)
893 {
894         char *queue = qe->parent->name;
895         struct localuser *o;
896         int found;
897         int numlines;
898         int status;
899         int sentringing = 0;
900         int numbusies = 0;
901         int numnochan = 0;
902         int orig = *to;
903         struct ast_frame *f;
904         struct localuser *peer = NULL;
905         struct ast_channel *watchers[AST_MAX_WATCHERS];
906         int pos;
907         struct ast_channel *winner;
908         struct ast_channel *in = qe->chan;
909         
910         while(*to && !peer) {
911                 o = outgoing;
912                 found = -1;
913                 pos = 1;
914                 numlines = 0;
915                 watchers[0] = in;
916                 while(o) {
917                         /* Keep track of important channels */
918                         if (o->stillgoing && o->chan) {
919                                 watchers[pos++] = o->chan;
920                                 found = 1;
921                         }
922                         o = o->next;
923                         numlines++;
924                 }
925                 if (found < 0) {
926                         if (numlines == (numbusies + numnochan)) {
927                                 ast_log(LOG_DEBUG, "Everyone is busy at this time\n");
928                         } else {
929                                 ast_log(LOG_NOTICE, "No one is answering queue '%s'\n", queue);
930                         }
931                         *to = 0;
932                         return NULL;
933                 }
934                 winner = ast_waitfor_n(watchers, pos, to);
935                 o = outgoing;
936                 while(o) {
937                         if (o->stillgoing && (o->chan) &&  (o->chan->_state == AST_STATE_UP)) {
938                                 if (!peer) {
939                                         if (option_verbose > 2)
940                                                 ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
941                                         peer = o;
942                                         *allowredir_in = o->allowredirect_in;
943                                         *allowredir_out = o->allowredirect_out;
944                                         *allowdisconnect_in = o->allowdisconnect_in;
945                                         *allowdisconnect_out = o->allowdisconnect_out;
946                                 }
947                         } else if (o->chan && (o->chan == winner)) {
948                                 if (!ast_strlen_zero(o->chan->call_forward)) {
949                                         char tmpchan[256]="";
950                                         char *stuff;
951                                         char *tech;
952                                         strncpy(tmpchan, o->chan->call_forward, sizeof(tmpchan) - 1);
953                                         if ((stuff = strchr(tmpchan, '/'))) {
954                                                 *stuff = '\0';
955                                                 stuff++;
956                                                 tech = tmpchan;
957                                         } else {
958                                                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", o->chan->call_forward, o->chan->context);
959                                                 stuff = tmpchan;
960                                                 tech = "Local";
961                                         }
962                                         /* Before processing channel, go ahead and check for forwarding */
963                                         if (option_verbose > 2)
964                                                 ast_verbose(VERBOSE_PREFIX_3 "Now forwarding %s to '%s/%s' (thanks to %s)\n", in->name, tech, stuff, o->chan->name);
965                                         /* Setup parameters */
966                                         o->chan = ast_request(tech, in->nativeformats, stuff, &status);
967                                         if (status != o->oldstatus) 
968                                                 update_dial_status(qe->parent, o->member, status);                                              
969                                         if (!o->chan) {
970                                                 ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s'\n", tech, stuff);
971                                                 o->stillgoing = 0;
972                                                 numnochan++;
973                                         } else {
974                                                 if (o->chan->cid.cid_num)
975                                                         free(o->chan->cid.cid_num);
976                                                 o->chan->cid.cid_num = NULL;
977                                                 if (o->chan->cid.cid_name)
978                                                         free(o->chan->cid.cid_name);
979                                                 o->chan->cid.cid_name = NULL;
980
981                                                 if (in->cid.cid_num) {
982                                                         o->chan->cid.cid_num = strdup(in->cid.cid_num);
983                                                         if (!o->chan->cid.cid_num)
984                                                                 ast_log(LOG_WARNING, "Out of memory\n");        
985                                                 }
986                                                 if (in->cid.cid_name) {
987                                                         o->chan->cid.cid_name = strdup(in->cid.cid_name);
988                                                         if (!o->chan->cid.cid_name)
989                                                                 ast_log(LOG_WARNING, "Out of memory\n");        
990                                                 }
991                                                 strncpy(o->chan->accountcode, in->accountcode, sizeof(o->chan->accountcode) - 1);
992                                                 o->chan->cdrflags = in->cdrflags;
993
994                                                 if (in->cid.cid_ani) {
995                                                         if (o->chan->cid.cid_ani)
996                                                                 free(o->chan->cid.cid_ani);
997                                                         o->chan->cid.cid_ani = malloc(strlen(in->cid.cid_ani) + 1);
998                                                         if (o->chan->cid.cid_ani)
999                                                                 strncpy(o->chan->cid.cid_ani, in->cid.cid_ani, strlen(in->cid.cid_ani) + 1);
1000                                                         else
1001                                                                 ast_log(LOG_WARNING, "Out of memory\n");
1002                                                 }
1003                                                 if (o->chan->cid.cid_rdnis) 
1004                                                         free(o->chan->cid.cid_rdnis);
1005                                                 if (!ast_strlen_zero(in->macroexten))
1006                                                         o->chan->cid.cid_rdnis = strdup(in->macroexten);
1007                                                 else
1008                                                         o->chan->cid.cid_rdnis = strdup(in->exten);
1009                                                 if (ast_call(o->chan, tmpchan, 0)) {
1010                                                         ast_log(LOG_NOTICE, "Failed to dial on local channel for call forward to '%s'\n", tmpchan);
1011                                                         o->stillgoing = 0;
1012                                                         ast_hangup(o->chan);
1013                                                         o->chan = NULL;
1014                                                         numnochan++;
1015                                                 }
1016                                         }
1017                                         /* Hangup the original channel now, in case we needed it */
1018                                         ast_hangup(winner);
1019                                         continue;
1020                                 }
1021                                 f = ast_read(winner);
1022                                 if (f) {
1023                                         if (f->frametype == AST_FRAME_CONTROL) {
1024                                                 switch(f->subclass) {
1025                                             case AST_CONTROL_ANSWER:
1026                                                         /* This is our guy if someone answered. */
1027                                                         if (!peer) {
1028                                                                 if (option_verbose > 2)
1029                                                                         ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
1030                                                                 peer = o;
1031                                                                 *allowredir_in = o->allowredirect_in;
1032                                                                 *allowredir_out = o->allowredirect_out;
1033                                                                 *allowdisconnect_in = o->allowdisconnect_out;
1034                                                                 *allowdisconnect_out = o->allowdisconnect_out;
1035                                                         }
1036                                                         break;
1037                                                 case AST_CONTROL_BUSY:
1038                                                         if (option_verbose > 2)
1039                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is busy\n", o->chan->name);
1040                                                         o->stillgoing = 0;
1041                                                         if (in->cdr)
1042                                                                 ast_cdr_busy(in->cdr);
1043                                                         ast_hangup(o->chan);
1044                                                         o->chan = NULL;
1045                                                         if (qe->parent->strategy)
1046                                                                 ring_one(qe, outgoing);
1047                                                         numbusies++;
1048                                                         break;
1049                                                 case AST_CONTROL_CONGESTION:
1050                                                         if (option_verbose > 2)
1051                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is circuit-busy\n", o->chan->name);
1052                                                         o->stillgoing = 0;
1053                                                         if (in->cdr)
1054                                                                 ast_cdr_busy(in->cdr);
1055                                                         ast_hangup(o->chan);
1056                                                         o->chan = NULL;
1057                                                         if (qe->parent->strategy)
1058                                                                 ring_one(qe, outgoing);
1059                                                         numbusies++;
1060                                                         break;
1061                                                 case AST_CONTROL_RINGING:
1062                                                         if (option_verbose > 2)
1063                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is ringing\n", o->chan->name);
1064                                                         if (!sentringing) {
1065 #if 0
1066                                                                 ast_indicate(in, AST_CONTROL_RINGING);
1067 #endif                                                          
1068                                                                 sentringing++;
1069                                                         }
1070                                                         break;
1071                                                 case AST_CONTROL_OFFHOOK:
1072                                                         /* Ignore going off hook */
1073                                                         break;
1074                                                 default:
1075                                                         ast_log(LOG_DEBUG, "Dunno what to do with control type %d\n", f->subclass);
1076                                                 }
1077                                         }
1078                                         ast_frfree(f);
1079                                 } else {
1080                                         o->stillgoing = 0;
1081                                         ast_hangup(o->chan);
1082                                         o->chan = NULL;
1083                                         if (qe->parent->strategy)
1084                                                 ring_one(qe, outgoing);
1085                                 }
1086                         }
1087                         o = o->next;
1088                 }
1089                 if (winner == in) {
1090                         f = ast_read(in);
1091 #if 0
1092                         if (f && (f->frametype != AST_FRAME_VOICE))
1093                                         printf("Frame type: %d, %d\n", f->frametype, f->subclass);
1094                         else if (!f || (f->frametype != AST_FRAME_VOICE))
1095                                 printf("Hangup received on %s\n", in->name);
1096 #endif
1097                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))) {
1098                                 /* Got hung up */
1099                                 *to=-1;
1100                                 return NULL;
1101                         }
1102                         if (f && (f->frametype == AST_FRAME_DTMF) && allowdisconnect_out && (f->subclass == '*')) {
1103                             if (option_verbose > 3)
1104                                         ast_verbose(VERBOSE_PREFIX_3 "User hit %c to disconnect call.\n", f->subclass);
1105                                 *to=0;
1106                                 return NULL;
1107                         }
1108                         if (f && (f->frametype == AST_FRAME_DTMF) && (f->subclass != '*') && valid_exit(qe, f->subclass)) {
1109                                 if (option_verbose > 3)
1110                                         ast_verbose(VERBOSE_PREFIX_3 "User pressed digit: %c", f->subclass);
1111                                 *to=0;
1112                                 *digit=f->subclass;
1113                                 return NULL;
1114                         }
1115                 }
1116                 if (!*to && (option_verbose > 2))
1117                         ast_verbose( VERBOSE_PREFIX_3 "Nobody picked up in %d ms\n", orig);
1118         }
1119
1120         return peer;
1121         
1122 }
1123
1124 static int is_our_turn(struct queue_ent *qe)
1125 {
1126         struct queue_ent *ch;
1127         int res;
1128
1129         /* Atomically read the parent head -- does not need a lock */
1130         ch = qe->parent->head;
1131         /* If we are now at the top of the head, break out */
1132         if (ch == qe) {
1133                 if (option_debug)
1134                         ast_log(LOG_DEBUG, "It's our turn (%s).\n", qe->chan->name);
1135                 res = 1;
1136         } else {
1137                 if (option_debug)
1138                         ast_log(LOG_DEBUG, "It's not our turn (%s).\n", qe->chan->name);
1139                 res = 0;
1140         }
1141         return res;
1142 }
1143
1144 static int wait_our_turn(struct queue_ent *qe, int ringing)
1145 {
1146         struct queue_ent *ch;
1147         int res = 0;
1148
1149         /* This is the holding pen for callers 2 through maxlen */
1150         for (;;) {
1151                 /* Atomically read the parent head -- does not need a lock */
1152                 ch = qe->parent->head;
1153
1154                 /* If we are now at the top of the head, break out */
1155                 if (ch == qe) {
1156                         if (option_debug)
1157                                 ast_log(LOG_DEBUG, "It's our turn (%s).\n", qe->chan->name);
1158                         break;
1159                 }
1160
1161                 /* If we have timed out, break out */
1162                 if (qe->expire && (time(NULL) > qe->expire))
1163                         break;
1164
1165                 /* leave the queue if no agents, if enabled */
1166                 if (has_no_members(qe->parent) && qe->parent->leavewhenempty) {
1167                         leave_queue(qe);
1168                         break;
1169                 }
1170
1171                 /* Make a position announcement, if enabled */
1172                 if (qe->parent->announcefrequency && !ringing)
1173                         say_position(qe);
1174
1175                 /* Wait a second before checking again */
1176                 res = ast_waitfordigit(qe->chan, RECHECK * 1000);
1177                 if (res)
1178                         break;
1179         }
1180         return res;
1181 }
1182
1183 static int update_queue(struct ast_call_queue *q, struct member *member)
1184 {
1185         struct member *cur;
1186         /* Since a reload could have taken place, we have to traverse the list to
1187                 be sure it's still valid */
1188         ast_mutex_lock(&q->lock);
1189         cur = q->members;
1190         while(cur) {
1191                 if (member == cur) {
1192                         time(&cur->lastcall);
1193                         cur->calls++;
1194                         break;
1195                 }
1196                 cur = cur->next;
1197         }
1198         q->callscompleted++;
1199         ast_mutex_unlock(&q->lock);
1200         return 0;
1201 }
1202
1203 static int calc_metric(struct ast_call_queue *q, struct member *mem, int pos, struct queue_ent *qe, struct localuser *tmp)
1204 {
1205         switch (q->strategy) {
1206         case QUEUE_STRATEGY_RINGALL:
1207                 /* Everyone equal, except for penalty */
1208                 tmp->metric = mem->penalty * 1000000;
1209                 break;
1210         case QUEUE_STRATEGY_ROUNDROBIN:
1211                 if (!pos) {
1212                         if (!q->wrapped) {
1213                                 /* No more channels, start over */
1214                                 q->rrpos = 0;
1215                         } else {
1216                                 /* Prioritize next entry */
1217                                 q->rrpos++;
1218                         }
1219                         q->wrapped = 0;
1220                 }
1221                 /* Fall through */
1222         case QUEUE_STRATEGY_RRMEMORY:
1223                 if (pos < q->rrpos) {
1224                         tmp->metric = 1000 + pos;
1225                 } else {
1226                         if (pos > q->rrpos) {
1227                                 /* Indicate there is another priority */
1228                                 q->wrapped = 1;
1229                         }
1230                         tmp->metric = pos;
1231                 }
1232                 tmp->metric += mem->penalty * 1000000;
1233                 break;
1234         case QUEUE_STRATEGY_RANDOM:
1235                 tmp->metric = rand() % 1000;
1236                 tmp->metric += mem->penalty * 1000000;
1237                 break;
1238         case QUEUE_STRATEGY_FEWESTCALLS:
1239                 tmp->metric = mem->calls;
1240                 tmp->metric += mem->penalty * 1000000;
1241                 break;
1242         case QUEUE_STRATEGY_LEASTRECENT:
1243                 if (!mem->lastcall)
1244                         tmp->metric = 0;
1245                 else
1246                         tmp->metric = 1000000 - (time(NULL) - mem->lastcall);
1247                 tmp->metric += mem->penalty * 1000000;
1248                 break;
1249         default:
1250                 ast_log(LOG_WARNING, "Can't calculate metric for unknown strategy %d\n", q->strategy);
1251                 break;
1252         }
1253         return 0;
1254 }
1255
1256 static int try_calling(struct queue_ent *qe, char *options, char *announceoverride, char *url, int *go_on)
1257 {
1258         struct member *cur;
1259         struct localuser *outgoing=NULL, *tmp = NULL;
1260         int to;
1261         int allowredir_in=0;
1262         int allowredir_out=0;
1263         int allowdisconnect_in=0;
1264         int allowdisconnect_out=0;
1265         char restofit[AST_MAX_EXTENSION];
1266         char oldexten[AST_MAX_EXTENSION]="";
1267         char oldcontext[AST_MAX_EXTENSION]="";
1268         char queuename[256]="";
1269         char *newnum;
1270         char *monitorfilename;
1271         struct ast_channel *peer;
1272         struct localuser *lpeer;
1273         struct member *member;
1274         int res = 0, bridge = 0;
1275         int zapx = 2;
1276         int x=0;
1277         char *announce = NULL;
1278         char digit = 0;
1279         time_t callstart;
1280         time_t now;
1281         struct ast_bridge_config config;
1282         /* Hold the lock while we setup the outgoing calls */
1283         ast_mutex_lock(&qe->parent->lock);
1284         if (option_debug)
1285                 ast_log(LOG_DEBUG, "%s is trying to call a queue member.\n", 
1286                                                         qe->chan->name);
1287         strncpy(queuename, qe->parent->name, sizeof(queuename) - 1);
1288         time(&now);
1289         cur = qe->parent->members;
1290         if (!ast_strlen_zero(qe->announce))
1291                 announce = qe->announce;
1292         if (announceoverride && !ast_strlen_zero(announceoverride))
1293                 announce = announceoverride;
1294         while(cur) {
1295                 /* Get a technology/[device:]number pair */
1296                 tmp = malloc(sizeof(struct localuser));
1297                 if (!tmp) {
1298                         ast_mutex_unlock(&qe->parent->lock);
1299                         ast_log(LOG_WARNING, "Out of memory\n");
1300                         goto out;
1301                 }
1302                 memset(tmp, 0, sizeof(struct localuser));
1303                 tmp->stillgoing = -1;
1304                 if (options) {
1305                         if (strchr(options, 't'))
1306                                 tmp->allowredirect_in = 1;
1307                         if (strchr(options, 'T'))
1308                                 tmp->allowredirect_out = 1;
1309                         if (strchr(options, 'r'))
1310                                 tmp->ringbackonly = 1;
1311                         if (strchr(options, 'm'))
1312                                 tmp->musiconhold = 1;
1313                         if (strchr(options, 'd'))
1314                                 tmp->dataquality = 1;
1315                         if (strchr(options, 'h'))
1316                                 tmp->allowdisconnect_in = 1;
1317                         if (strchr(options, 'H'))
1318                                 tmp->allowdisconnect_out = 1;
1319                         if ((strchr(options, 'n')) && (now - qe->start >= qe->parent->timeout))
1320                                 *go_on = 1;
1321                 }
1322                 if (option_debug) {
1323                         if (url)
1324                                 ast_log(LOG_DEBUG, "Queue with URL=%s_\n", url);
1325                         else 
1326                                 ast_log(LOG_DEBUG, "Simple queue (no URL)\n");
1327                 }
1328
1329                 tmp->member = cur;              /* Never directly dereference!  Could change on reload */
1330                 tmp->oldstatus = cur->status;
1331                 tmp->lastcall = cur->lastcall;
1332                 strncpy(tmp->interface, cur->interface, sizeof(tmp->interface)-1);
1333                 /* If we're dialing by extension, look at the extension to know what to dial */
1334                 if ((newnum = strstr(tmp->interface, "/BYEXTENSION"))) {
1335                         newnum++;
1336                         strncpy(restofit, newnum + strlen("BYEXTENSION"), sizeof(restofit) - 1);
1337                         snprintf(newnum, sizeof(tmp->interface) - (newnum - tmp->interface), "%s%s", qe->chan->exten, restofit);
1338                         if (option_debug)
1339                                 ast_log(LOG_DEBUG, "Dialing by extension %s\n", tmp->interface);
1340                 }
1341                 /* Special case: If we ring everyone, go ahead and ring them, otherwise
1342                    just calculate their metric for the appropriate strategy */
1343                 calc_metric(qe->parent, cur, x++, qe, tmp);
1344                 /* Put them in the list of outgoing thingies...  We're ready now. 
1345                    XXX If we're forcibly removed, these outgoing calls won't get
1346                    hung up XXX */
1347                 tmp->next = outgoing;
1348                 outgoing = tmp;         
1349                 /* If this line is up, don't try anybody else */
1350                 if (outgoing->chan && (outgoing->chan->_state == AST_STATE_UP))
1351                         break;
1352
1353                 cur = cur->next;
1354         }
1355         if (qe->parent->timeout)
1356                 to = qe->parent->timeout * 1000;
1357         else
1358                 to = -1;
1359         ring_one(qe, outgoing);
1360         ast_mutex_unlock(&qe->parent->lock);
1361         lpeer = wait_for_answer(qe, outgoing, &to, &allowredir_in, &allowredir_out, &allowdisconnect_in, &allowdisconnect_out, &digit);
1362         ast_mutex_lock(&qe->parent->lock);
1363         if (qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY) {
1364                 store_next(qe, outgoing);
1365         }
1366         ast_mutex_unlock(&qe->parent->lock);
1367         if (lpeer)
1368                 peer = lpeer->chan;
1369         else
1370                 peer = NULL;
1371         if (!peer) {
1372                 if (to) {
1373                         /* Musta gotten hung up */
1374                         record_abandoned(qe);
1375                         res = -1;
1376                 } else {
1377                         if (digit && valid_exit(qe, digit))
1378                                 res=digit;
1379                         else
1380                                 /* Nobody answered, next please? */
1381                                 res=0;
1382                 }
1383                 if (option_debug)
1384                         ast_log(LOG_DEBUG, "%s: Nobody answered.\n", qe->chan->name);
1385                 goto out;
1386         }
1387         if (peer) {
1388                 /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
1389                    we will always return with -1 so that it is hung up properly after the 
1390                    conversation.  */
1391                 qe->handled++;
1392                 if (!strcmp(qe->chan->type,"Zap")) {
1393                         if (tmp->dataquality) zapx = 0;
1394                         ast_channel_setoption(qe->chan,AST_OPTION_TONE_VERIFY,&zapx,sizeof(char),0);
1395                 }                       
1396                 if (!strcmp(peer->type,"Zap")) {
1397                         if (tmp->dataquality) zapx = 0;
1398                         ast_channel_setoption(peer,AST_OPTION_TONE_VERIFY,&zapx,sizeof(char),0);
1399                 }
1400                 /* Update parameters for the queue */
1401                 recalc_holdtime(qe);
1402                 member = lpeer->member;
1403                 hanguptree(outgoing, peer);
1404                 outgoing = NULL;
1405                 if (announce || qe->parent->reportholdtime || qe->parent->memberdelay) {
1406                         int res2;
1407                         res2 = ast_autoservice_start(qe->chan);
1408                         if (!res2) {
1409                                 if (qe->parent->memberdelay) {
1410                                         ast_log(LOG_NOTICE, "Delaying member connect for %d seconds\n", qe->parent->memberdelay);
1411                                         res2 |= ast_safe_sleep(peer, qe->parent->memberdelay * 1000);
1412                                 }
1413                                 if (!res2 && announce) {
1414                                         if (play_file(peer, announce))
1415                                                 ast_log(LOG_WARNING, "Announcement file '%s' is unavailable, continuing anyway...\n", announce);
1416                                 }
1417                                 if (!res2 && qe->parent->reportholdtime) {
1418                                         if (!play_file(peer, qe->parent->sound_reporthold)) {
1419                                                 int holdtime;
1420                                                 time_t now;
1421
1422                                                 time(&now);
1423                                                 holdtime = abs((now - qe->start) / 60);
1424                                                 if (holdtime < 2) {
1425                                                         play_file(peer, qe->parent->sound_lessthan);
1426                                                         ast_say_number(peer, 2, AST_DIGIT_ANY, peer->language, NULL);
1427                                                 } else 
1428                                                         ast_say_number(peer, holdtime, AST_DIGIT_ANY, peer->language, NULL);
1429                                                 play_file(peer, qe->parent->sound_minutes);
1430                                         }
1431                                 }
1432                         }
1433                         res2 |= ast_autoservice_stop(qe->chan);
1434                         if (res2) {
1435                                 /* Agent must have hung up */
1436                                 ast_log(LOG_WARNING, "Agent on %s hungup on the customer.  They're going to be pissed.\n", peer->name);
1437                                 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "AGENTDUMP", "%s", "");
1438                                 ast_hangup(peer);
1439                                 return -1;
1440                         }
1441                 }
1442                 /* Stop music on hold */
1443                 ast_moh_stop(qe->chan);
1444                 /* If appropriate, log that we have a destination channel */
1445                 if (qe->chan->cdr)
1446                         ast_cdr_setdestchan(qe->chan->cdr, peer->name);
1447                 /* Make sure channels are compatible */
1448                 res = ast_channel_make_compatible(qe->chan, peer);
1449                 if (res < 0) {
1450                         ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "SYSCOMPAT", "%s", "");
1451                         ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", qe->chan->name, peer->name);
1452                         ast_hangup(peer);
1453                         return -1;
1454                 }
1455                 /* Begin Monitoring */
1456                 if (qe->parent->monfmt && *qe->parent->monfmt) {
1457                         monitorfilename = pbx_builtin_getvar_helper( qe->chan, "MONITOR_FILENAME");
1458                         if(monitorfilename) {
1459                                 ast_monitor_start( peer, qe->parent->monfmt, monitorfilename, 1 );
1460                         } else {
1461                                 ast_monitor_start( peer, qe->parent->monfmt, qe->chan->cdr->uniqueid, 1 );
1462                         }
1463                         if(qe->parent->monjoin) {
1464                                 ast_monitor_setjoinfiles( peer, 1);
1465                         }
1466                 }
1467                 /* Drop out of the queue at this point, to prepare for next caller */
1468                 leave_queue(qe);                        
1469                 if( url && !ast_strlen_zero(url) && ast_channel_supports_html(peer) ) {
1470                         if (option_debug)
1471                                 ast_log(LOG_DEBUG, "app_queue: sendurl=%s.\n", url);
1472                         ast_channel_sendurl( peer, url );
1473                 }
1474                 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "CONNECT", "%ld", (long)time(NULL) - qe->start);
1475                 strncpy(oldcontext, qe->chan->context, sizeof(oldcontext) - 1);
1476                 strncpy(oldexten, qe->chan->exten, sizeof(oldexten) - 1);
1477                 time(&callstart);
1478
1479                 memset(&config,0,sizeof(struct ast_bridge_config));
1480         config.allowredirect_in = allowredir_in;
1481         config.allowredirect_out = allowredir_out;
1482         config.allowdisconnect_in = allowdisconnect_in;
1483         config.allowdisconnect_out = allowdisconnect_out;
1484         bridge = ast_bridge_call(qe->chan,peer,&config);
1485
1486                 if (strcasecmp(oldcontext, qe->chan->context) || strcasecmp(oldexten, qe->chan->exten)) {
1487                         ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "TRANSFER", "%s|%s", qe->chan->exten, qe->chan->context);
1488                 } else if (qe->chan->_softhangup) {
1489                         ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "COMPLETECALLER", "%ld|%ld", (long)(callstart - qe->start), (long)(time(NULL) - callstart));
1490                 } else {
1491                         ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "COMPLETEAGENT", "%ld|%ld", (long)(callstart - qe->start), (long)(time(NULL) - callstart));
1492                 }
1493
1494                 if(bridge != AST_PBX_NO_HANGUP_PEER)
1495                         ast_hangup(peer);
1496                 update_queue(qe->parent, member);
1497                 if( bridge == 0 ) res=1; /* JDG: bridge successfull, leave app_queue */
1498                 else res = bridge; /* bridge error, stay in the queue */
1499         }       
1500 out:
1501         hanguptree(outgoing, NULL);
1502         return res;
1503 }
1504
1505 static int wait_a_bit(struct queue_ent *qe)
1506 {
1507         /* Don't need to hold the lock while we setup the outgoing calls */
1508         int retrywait = qe->parent->retry * 1000;
1509         return ast_waitfordigit(qe->chan, retrywait);
1510 }
1511
1512 /* [PHM 06/26/03] */
1513
1514 static struct member * interface_exists(struct ast_call_queue *q, char *interface)
1515 {
1516         struct member *mem;
1517
1518         if (q)
1519                 for (mem = q->members; mem; mem = mem->next)
1520                         if (!strcmp(interface, mem->interface))
1521                                 return mem;
1522
1523         return NULL;
1524 }
1525
1526
1527 static struct member *create_queue_node(char *interface, int penalty)
1528 {
1529         struct member *cur;
1530         
1531         /* Add a new member */
1532
1533         cur = malloc(sizeof(struct member));
1534
1535         if (cur) {
1536                 memset(cur, 0, sizeof(struct member));
1537                 cur->penalty = penalty;
1538                 strncpy(cur->interface, interface, sizeof(cur->interface) - 1);
1539                 if (!strchr(cur->interface, '/'))
1540                         ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
1541                 cur->status = ast_device_state(interface);
1542         }
1543
1544         return cur;
1545 }
1546
1547 /* Dump all members in a specific queue to the databse
1548  *
1549  * <pm_family>/<queuename> = <interface>;<penalty>;...
1550  *
1551  */
1552 static void dump_queue_members(struct ast_call_queue *pm_queue)
1553 {
1554         struct member *cur_member = NULL;
1555         char value[PM_MAX_LEN];
1556         int value_len = 0;
1557         int res;
1558
1559         memset(value, 0, sizeof(value));
1560
1561         if (pm_queue) {
1562                 cur_member = pm_queue->members;
1563                 while (cur_member) {
1564                         if (cur_member->dynamic) {
1565                                 value_len = strlen(value);
1566                                 res = snprintf(value+value_len, sizeof(value)-value_len, "%s;%d;", cur_member->interface, cur_member->penalty);
1567                                 if (res != strlen(value + value_len)) {
1568                                         ast_log(LOG_WARNING, "Could not create persistent member string, out of space\n");
1569                                         break;
1570                                 }
1571                         }                                       
1572                         cur_member = cur_member->next;
1573                 }
1574
1575                 if (!ast_strlen_zero(value) && !cur_member) {
1576                         if (ast_db_put(pm_family, pm_queue->name, value))
1577                             ast_log(LOG_WARNING, "failed to create persistent dynamic entry!\n");
1578                 } else {
1579                         /* Delete the entry if the queue is empty or there is an error */
1580                     ast_db_del(pm_family, pm_queue->name);
1581                 }
1582
1583         }
1584
1585 }
1586
1587 static int remove_from_queue(char *queuename, char *interface)
1588 {
1589         struct ast_call_queue *q;
1590         struct member *last_member, *look;
1591         int res = RES_NOSUCHQUEUE;
1592
1593         ast_mutex_lock(&qlock);
1594         for (q = queues ; q ; q = q->next) {
1595                 ast_mutex_lock(&q->lock);
1596                 if (!strcmp(q->name, queuename)) {
1597                         if ((last_member = interface_exists(q, interface))) {
1598                                 if ((look = q->members) == last_member) {
1599                                         q->members = last_member->next;
1600                                 } else {
1601                                         while (look != NULL) {
1602                                                 if (look->next == last_member) {
1603                                                         look->next = last_member->next;
1604                                                         break;
1605                                                 } else {
1606                                                          look = look->next;
1607                                                 }
1608                                         }
1609                                 }
1610                                 manager_event(EVENT_FLAG_AGENT, "QueueMemberRemoved",
1611                                                 "Queue: %s\r\n"
1612                                                 "Location: %s\r\n",
1613                                         q->name, last_member->interface);
1614                                 free(last_member);
1615
1616                                 if (queue_persistent_members)
1617                                     dump_queue_members(q);
1618
1619                                 res = RES_OKAY;
1620                         } else {
1621                                 res = RES_EXISTS;
1622                         }
1623                         ast_mutex_unlock(&q->lock);
1624                         break;
1625                 }
1626                 ast_mutex_unlock(&q->lock);
1627         }
1628         ast_mutex_unlock(&qlock);
1629         return res;
1630 }
1631
1632 static int add_to_queue(char *queuename, char *interface, int penalty)
1633 {
1634         struct ast_call_queue *q;
1635         struct member *new_member;
1636         int res = RES_NOSUCHQUEUE;
1637
1638         ast_mutex_lock(&qlock);
1639         for (q = queues ; q ; q = q->next) {
1640                 ast_mutex_lock(&q->lock);
1641                 if (!strcmp(q->name, queuename)) {
1642                         if (interface_exists(q, interface) == NULL) {
1643                                 new_member = create_queue_node(interface, penalty);
1644
1645                                 if (new_member != NULL) {
1646                                         new_member->dynamic = 1;
1647                                         new_member->next = q->members;
1648                                         q->members = new_member;
1649                                         manager_event(EVENT_FLAG_AGENT, "QueueMemberAdded",
1650                                                 "Queue: %s\r\n"
1651                                                 "Location: %s\r\n"
1652                                                 "Membership: %s\r\n"
1653                                                 "Penalty: %d\r\n"
1654                                                 "CallsTaken: %d\r\n"
1655                                                 "LastCall: %ld\r\n"
1656                                                 "Status: %d\r\n",
1657                                         q->name, new_member->interface, new_member->dynamic ? "dynamic" : "static",
1658                                         new_member->penalty, new_member->calls, new_member->lastcall, new_member->status);
1659                                         
1660                                         if (queue_persistent_members)
1661                                             dump_queue_members(q);
1662
1663                                         res = RES_OKAY;
1664                                 } else {
1665                                         res = RES_OUTOFMEMORY;
1666                                 }
1667                         } else {
1668                                 res = RES_EXISTS;
1669                         }
1670                         ast_mutex_unlock(&q->lock);
1671                         break;
1672                 }
1673                 ast_mutex_unlock(&q->lock);
1674         }
1675         ast_mutex_unlock(&qlock);
1676         return res;
1677 }
1678
1679 /* Add members saved in the queue members DB file saves
1680  * created by dump_queue_members(), back into the queues */
1681 static void reload_queue_members(void)
1682 {
1683         char *cur_pm_ptr;       
1684         char *pm_queue_name;
1685         char *pm_interface;
1686         char *pm_penalty_tok;
1687         int pm_penalty = 0;
1688         struct ast_db_entry *pm_db_tree = NULL;
1689         int pm_family_len = 0;
1690         struct ast_call_queue *cur_queue = NULL;
1691         char queue_data[PM_MAX_LEN];
1692
1693         pm_db_tree = ast_db_gettree(pm_family, NULL);
1694
1695         pm_family_len = strlen(pm_family);
1696         ast_mutex_lock(&qlock);
1697         /* Each key in 'pm_family' is the name of a specific queue in which
1698          * we will reload members into. */
1699         while (pm_db_tree) {
1700                 pm_queue_name = pm_db_tree->key+pm_family_len+2;
1701
1702                 cur_queue = queues;
1703                 while (cur_queue) {
1704                         ast_mutex_lock(&cur_queue->lock);
1705                         
1706                         if (strcmp(pm_queue_name, cur_queue->name) == 0)
1707                             break;
1708                         
1709                         ast_mutex_unlock(&cur_queue->lock);
1710                         
1711                         cur_queue = cur_queue->next;
1712                 }
1713
1714                 if (!cur_queue) {
1715                         /* If the queue no longer exists, remove it from the
1716                          * database */
1717                         ast_db_del(pm_family, pm_queue_name);
1718                         pm_db_tree = pm_db_tree->next;
1719                         continue;
1720                 } else
1721                     ast_mutex_unlock(&cur_queue->lock);
1722
1723                 if (!ast_db_get(pm_family, pm_queue_name, queue_data, PM_MAX_LEN)) {
1724                         /* Parse each <interface>;<penalty>; from the value of the
1725                          * queuename key and add it to the respective queue */
1726                         cur_pm_ptr = queue_data;
1727                         while ((pm_interface = strsep(&cur_pm_ptr, ";"))) {
1728                                 if (!(pm_penalty_tok = strsep(&cur_pm_ptr, ";"))) {
1729                                         ast_log(LOG_WARNING, "Error parsing corrupted Queue DB string for '%s'\n", pm_queue_name);
1730                                         break;
1731                                 }
1732                                 pm_penalty = strtol(pm_penalty_tok, NULL, 10);
1733                                 if (errno == ERANGE) {
1734                                         ast_log(LOG_WARNING, "Error converting penalty: %s: Out of range.\n", pm_penalty_tok);
1735                                         break;
1736                                 }
1737         
1738                                 if (option_debug)
1739                                     ast_log(LOG_DEBUG, "Reload Members: Queue: %s  Member: %s  Penalty: %d\n", pm_queue_name, pm_interface, pm_penalty);
1740         
1741                                 if (add_to_queue(pm_queue_name, pm_interface, pm_penalty) == RES_OUTOFMEMORY) {
1742                                         ast_log(LOG_ERROR, "Out of Memory\n");
1743                                         break;
1744                                 }
1745                         }
1746                 }
1747                 
1748                 pm_db_tree = pm_db_tree->next;
1749         }
1750
1751         ast_log(LOG_NOTICE, "Queue members sucessfully reloaded from database.\n");
1752         ast_mutex_unlock(&qlock);
1753         if (pm_db_tree) {
1754                 ast_db_freetree(pm_db_tree);
1755                 pm_db_tree = NULL;
1756         }
1757 }
1758
1759 static int rqm_exec(struct ast_channel *chan, void *data)
1760 {
1761         int res=-1;
1762         struct localuser *u;
1763         char *info, *queuename;
1764         char tmpchan[256]="";
1765         char *interface = NULL;
1766
1767         if (!data) {
1768                 ast_log(LOG_WARNING, "RemoveQueueMember requires an argument (queuename[|interface])\n");
1769                 return -1;
1770         }
1771
1772         info = ast_strdupa((char *)data);
1773         if (!info) {
1774                 ast_log(LOG_ERROR, "Out of memory\n");
1775                 return -1;
1776         }
1777
1778         LOCAL_USER_ADD(u);
1779
1780         queuename = info;
1781         if (queuename) {
1782                 interface = strchr(queuename, '|');
1783                 if (interface) {
1784                         *interface = '\0';
1785                         interface++;
1786                 }
1787                 else {
1788                         strncpy(tmpchan, chan->name, sizeof(tmpchan) - 1);
1789                         interface = strrchr(tmpchan, '-');
1790                         if (interface)
1791                                 *interface = '\0';
1792                         interface = tmpchan;
1793                 }
1794         }
1795
1796         switch (remove_from_queue(queuename, interface)) {
1797         case RES_OKAY:
1798                 ast_log(LOG_NOTICE, "Removed interface '%s' from queue '%s'\n", interface, queuename);
1799                 res = 0;
1800                 break;
1801         case RES_EXISTS:
1802                 ast_log(LOG_WARNING, "Unable to remove interface '%s' from queue '%s': Not there\n", interface, queuename);
1803                 if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 101, chan->cid.cid_num)) {
1804                         chan->priority += 100;
1805                 }
1806                 res = 0;
1807                 break;
1808         case RES_NOSUCHQUEUE:
1809                 ast_log(LOG_WARNING, "Unable to remove interface from queue '%s': No such queue\n", queuename);
1810                 res = 0;
1811                 break;
1812         case RES_OUTOFMEMORY:
1813                 ast_log(LOG_ERROR, "Out of memory\n");
1814                 break;
1815         }
1816
1817         LOCAL_USER_REMOVE(u);
1818         return res;
1819 }
1820
1821 static int aqm_exec(struct ast_channel *chan, void *data)
1822 {
1823         int res=-1;
1824         struct localuser *u;
1825         char *queuename;
1826         char *info;
1827         char tmpchan[512]="";
1828         char *interface=NULL;
1829         char *penaltys=NULL;
1830         int penalty = 0;
1831
1832         if (!data) {
1833                 ast_log(LOG_WARNING, "AddQueueMember requires an argument (queuename[|[interface][|penalty]])\n");
1834                 return -1;
1835         }
1836
1837         info = ast_strdupa((char *)data);
1838         if (!info) {
1839                 ast_log(LOG_ERROR, "Out of memory\n");
1840                 return -1;
1841         }
1842         LOCAL_USER_ADD(u);
1843
1844         queuename = info;
1845         if (queuename) {
1846                 interface = strchr(queuename, '|');
1847                 if (interface) {
1848                         *interface = '\0';
1849                         interface++;
1850                 }
1851                 if (interface) {
1852                         penaltys = strchr(interface, '|');
1853                         if (penaltys) {
1854                                 *penaltys = '\0';
1855                                 penaltys++;
1856                         }
1857                 }
1858                 if (!interface || ast_strlen_zero(interface)) {
1859                         strncpy(tmpchan, chan->name, sizeof(tmpchan) - 1);
1860                         interface = strrchr(tmpchan, '-');
1861                         if (interface)
1862                                 *interface = '\0';
1863                         interface = tmpchan;
1864                 }
1865                 if (penaltys && strlen(penaltys)) {
1866                         if ((sscanf(penaltys, "%d", &penalty) != 1) || penalty < 0) {
1867                                 ast_log(LOG_WARNING, "Penalty '%s' is invalid, must be an integer >= 0\n", penaltys);
1868                                 penalty = 0;
1869                         }
1870                 }
1871         }
1872
1873         switch (add_to_queue(queuename, interface, penalty)) {
1874         case RES_OKAY:
1875                 ast_log(LOG_NOTICE, "Added interface '%s' to queue '%s'\n", interface, queuename);
1876                 res = 0;
1877                 break;
1878         case RES_EXISTS:
1879                 ast_log(LOG_WARNING, "Unable to add interface '%s' to queue '%s': Already there\n", interface, queuename);
1880                 if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 101, chan->cid.cid_num)) {
1881                         chan->priority += 100;
1882                 }
1883                 res = 0;
1884                 break;
1885         case RES_NOSUCHQUEUE:
1886                 ast_log(LOG_WARNING, "Unable to add interface to queue '%s': No such queue\n", queuename);
1887                 res = 0;
1888                 break;
1889         case RES_OUTOFMEMORY:
1890                 ast_log(LOG_ERROR, "Out of memory\n");
1891                 break;
1892         }
1893
1894         LOCAL_USER_REMOVE(u);
1895         return res;
1896 }
1897
1898 static int queue_exec(struct ast_channel *chan, void *data)
1899 {
1900         int res=-1;
1901         int ringing=0;
1902         struct localuser *u;
1903         char *queuename;
1904         char info[512];
1905         char *info_ptr = info;
1906         char *options = NULL;
1907         char *url = NULL;
1908         char *announceoverride = NULL;
1909         char *user_priority;
1910         int prio;
1911         char *queuetimeoutstr = NULL;
1912
1913         /* whether to exit Queue application after the timeout hits */
1914         int go_on = 0;
1915
1916         /* Our queue entry */
1917         struct queue_ent qe;
1918         
1919         if (!data) {
1920                 ast_log(LOG_WARNING, "Queue requires an argument (queuename[|[timeout][|URL]])\n");
1921                 return -1;
1922         }
1923         
1924         LOCAL_USER_ADD(u);
1925
1926         /* Setup our queue entry */
1927         memset(&qe, 0, sizeof(qe));
1928         qe.start = time(NULL);
1929         
1930         /* Parse our arguments XXX Check for failure XXX */
1931         strncpy(info, (char *) data, sizeof(info) - 1);
1932         queuename = strsep(&info_ptr, "|");
1933         options = strsep(&info_ptr, "|");
1934         url = strsep(&info_ptr, "|");
1935         announceoverride = strsep(&info_ptr, "|");
1936         queuetimeoutstr = info_ptr;
1937
1938         /* set the expire time based on the supplied timeout; */
1939         if (queuetimeoutstr)
1940                 qe.expire = qe.start + atoi(queuetimeoutstr);
1941         else
1942                 qe.expire = 0;
1943
1944         /* Get the priority from the variable ${QUEUE_PRIO} */
1945         user_priority = pbx_builtin_getvar_helper(chan, "QUEUE_PRIO");
1946         if (user_priority) {
1947                 if (sscanf(user_priority, "%d", &prio) == 1) {
1948                         if (option_debug)
1949                                 ast_log(LOG_DEBUG, "%s: Got priority %d from ${QUEUE_PRIO}.\n",
1950                                                                 chan->name, prio);
1951                 } else {
1952                         ast_log(LOG_WARNING, "${QUEUE_PRIO}: Invalid value (%s), channel %s.\n",
1953                                                         user_priority, chan->name);
1954                         prio = 0;
1955                 }
1956         } else {
1957                 if (option_debug)
1958                         ast_log(LOG_DEBUG, "NO QUEUE_PRIO variable found. Using default.\n");
1959                 prio = 0;
1960         }
1961
1962         if (options) {
1963                 if (strchr(options, 'r')) {
1964                         ringing = 1;
1965                 }
1966         }
1967
1968 /*      if (option_debug)  */
1969                 ast_log(LOG_DEBUG, "queue: %s, options: %s, url: %s, announce: %s, expires: %ld, priority: %d\n",
1970                                 queuename, options, url, announceoverride, (long)qe.expire, (int)prio);
1971
1972         qe.chan = chan;
1973         qe.prio = (int)prio;
1974         qe.last_pos_said = 0;
1975         qe.last_pos = 0;
1976         if (!join_queue(queuename, &qe)) {
1977                 ast_queue_log(queuename, chan->uniqueid, "NONE", "ENTERQUEUE", "%s|%s", url ? url : "", chan->cid.cid_num ? chan->cid.cid_num : "");
1978                 /* Start music on hold */
1979 check_turns:
1980                 if (ringing) {
1981                         ast_indicate(chan, AST_CONTROL_RINGING);
1982                 } else {              
1983                         ast_moh_start(chan, qe.moh);
1984                 }
1985                 for (;;) {
1986                         /* This is the wait loop for callers 2 through maxlen */
1987
1988                         res = wait_our_turn(&qe, ringing);
1989                         /* If they hungup, return immediately */
1990                         if (res < 0) {
1991                                 /* Record this abandoned call */
1992                                 record_abandoned(&qe);
1993                                 ast_queue_log(queuename, chan->uniqueid, "NONE", "ABANDON", "%d|%d|%ld", qe.pos, qe.opos, (long)time(NULL) - qe.start);
1994                                 if (option_verbose > 2) {
1995                                         ast_verbose(VERBOSE_PREFIX_3 "User disconnected while waiting their turn\n");
1996                                         res = -1;
1997                                 }
1998                                 break;
1999                         }
2000                         if (!res) 
2001                                 break;
2002                         if (valid_exit(&qe, res)) {
2003                                 ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHKEY", "%c|%d", res, qe.pos);
2004                                 break;
2005                         }
2006                 }
2007                 if (!res) {
2008                         int makeannouncement = 0;
2009                         for (;;) {
2010                                 /* This is the wait loop for the head caller*/
2011                                 /* To exit, they may get their call answered; */
2012                                 /* they may dial a digit from the queue context; */
2013                                 /* or, they may timeout. */
2014
2015                                 /* Leave if we have exceeded our queuetimeout */
2016                                 if (qe.expire && (time(NULL) > qe.expire)) {
2017                                         res = 0;
2018                                         break;
2019                                 }
2020
2021                                 if (makeannouncement) {
2022                                         /* Make a position announcement, if enabled */
2023                                         if (qe.parent->announcefrequency && !ringing)
2024                                                 say_position(&qe);
2025                                 }
2026                                 makeannouncement = 1;
2027
2028                                 /* Try calling all queue members for 'timeout' seconds */
2029                                 res = try_calling(&qe, options, announceoverride, url, &go_on);
2030                                 if (res) {
2031                                         if (res < 0) {
2032                                                 if (!qe.handled)
2033                                                         ast_queue_log(queuename, chan->uniqueid, "NONE", "ABANDON", "%d|%d|%ld", qe.pos, qe.opos, (long)time(NULL) - qe.start);
2034                                         } else if (res > 0)
2035                                                 ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHKEY", "%c|%d", res, qe.pos);
2036                                         break;
2037                                 }
2038
2039                                 /* leave the queue if no agents, if enabled */
2040                                 if (has_no_members(qe.parent) && (qe.parent->leavewhenempty)) {
2041                                         res = 0;
2042                                         break;
2043                                 }
2044
2045                                 /* Leave if we have exceeded our queuetimeout */
2046                                 if (qe.expire && (time(NULL) > qe.expire)) {
2047                                         res = 0;
2048                                         break;
2049                                 }
2050
2051                                 /* OK, we didn't get anybody; wait for 'retry' seconds; may get a digit to exit with */
2052                                 res = wait_a_bit(&qe);
2053                                 if (res < 0) {
2054                                         ast_queue_log(queuename, chan->uniqueid, "NONE", "ABANDON", "%d|%d|%ld", qe.pos, qe.opos, (long)time(NULL) - qe.start);
2055                                         if (option_verbose > 2) {
2056                                                 ast_verbose(VERBOSE_PREFIX_3 "User disconnected when they almost made it\n");
2057                                                 res = -1;
2058                                         }
2059                                         break;
2060                                 }
2061                                 if (res && valid_exit(&qe, res)) {
2062                                         ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHKEY", "%c|%d", res, qe.pos);
2063                                         break;
2064                                 }
2065                                 /* exit after 'timeout' cycle if 'n' option enabled */
2066                                 if (go_on) {
2067                                         if (option_verbose > 2) {
2068                                                 ast_verbose(VERBOSE_PREFIX_3 "Exiting on time-out cycle\n");
2069                                                 res = -1;
2070                                         }
2071                                         ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHTIMEOUT", "%d", qe.pos);
2072                                         res = 0;
2073                                         break;
2074                                 }
2075                                 /* Since this is a priority queue and 
2076                                  * it is not sure that we are still at the head
2077                                  * of the queue, go and check for our turn again.
2078                                  */
2079                                 if (!is_our_turn(&qe)) {
2080                                         ast_log(LOG_DEBUG, "Darn priorities, going back in queue (%s)!\n",
2081                                                                 qe.chan->name);
2082                                         goto check_turns;
2083                                 }
2084                         }
2085                 }
2086                 /* Don't allow return code > 0 */
2087                 if (res >= 0 && res != AST_PBX_KEEPALIVE) {
2088                         res = 0;        
2089                         if (ringing) {
2090                                 ast_indicate(chan, -1);
2091                         } else {
2092                                 ast_moh_stop(chan);
2093                         }                       
2094                         ast_stopstream(chan);
2095                 }
2096                 leave_queue(&qe);
2097         } else {
2098                 ast_log(LOG_WARNING, "Unable to join queue '%s'\n", queuename);
2099                 res =  0;
2100         }
2101         LOCAL_USER_REMOVE(u);
2102         return res;
2103 }
2104
2105 static void reload_queues(void)
2106 {
2107         struct ast_call_queue *q, *ql, *qn;
2108         struct ast_config *cfg;
2109         char *cat, *tmp;
2110         struct ast_variable *var;
2111         struct member *prev, *cur;
2112         int new;
2113         char *general_val = NULL;
2114         
2115         cfg = ast_load("queues.conf");
2116         if (!cfg) {
2117                 ast_log(LOG_NOTICE, "No call queueing config file, so no call queues\n");
2118                 return;
2119         }
2120         ast_mutex_lock(&qlock);
2121         /* Mark all queues as dead for the moment */
2122         q = queues;
2123         while(q) {
2124                 q->dead = 1;
2125                 q = q->next;
2126         }
2127         /* Chug through config file */
2128         cat = ast_category_browse(cfg, NULL);
2129         while(cat) {
2130                 if (strcasecmp(cat, "general")) {
2131                         /* Look for an existing one */
2132                         q = queues;
2133                         while(q) {
2134                                 if (!strcmp(q->name, cat))
2135                                         break;
2136                                 q = q->next;
2137                         }
2138                         if (!q) {
2139                                 /* Make one then */
2140                                 q = malloc(sizeof(struct ast_call_queue));
2141                                 if (q) {
2142                                         /* Initialize it */
2143                                         memset(q, 0, sizeof(struct ast_call_queue));
2144                                         ast_mutex_init(&q->lock);
2145                                         strncpy(q->name, cat, sizeof(q->name) - 1);
2146                                         new = 1;
2147                                 } else new = 0;
2148                         } else
2149                                         new = 0;
2150                         if (q) {
2151                                 if (!new) 
2152                                         ast_mutex_lock(&q->lock);
2153                                 /* Re-initialize the queue */
2154                                 q->dead = 0;
2155                                 q->retry = 0;
2156                                 q->timeout = -1;
2157                                 q->maxlen = 0;
2158                                 q->announcefrequency = 0;
2159                                 q->announceholdtime = 0;
2160                                 q->roundingseconds = 0; /* Default - don't announce seconds */
2161                                 q->holdtime = 0;
2162                                 q->callscompleted = 0;
2163                                 q->callsabandoned = 0;
2164                                 q->callscompletedinsl = 0;
2165                                 q->servicelevel = 0;
2166                                 q->wrapuptime = 0;
2167                                 free_members(q, 0);
2168                                 q->moh[0] = '\0';
2169                                 q->announce[0] = '\0';
2170                                 q->context[0] = '\0';
2171                                 q->monfmt[0] = '\0';
2172                                 strncpy(q->sound_next, "queue-youarenext", sizeof(q->sound_next) - 1);
2173                                 strncpy(q->sound_thereare, "queue-thereare", sizeof(q->sound_thereare) - 1);
2174                                 strncpy(q->sound_calls, "queue-callswaiting", sizeof(q->sound_calls) - 1);
2175                                 strncpy(q->sound_holdtime, "queue-holdtime", sizeof(q->sound_holdtime) - 1);
2176                                 strncpy(q->sound_minutes, "queue-minutes", sizeof(q->sound_minutes) - 1);
2177                                 strncpy(q->sound_seconds, "queue-seconds", sizeof(q->sound_seconds) - 1);
2178                                 strncpy(q->sound_thanks, "queue-thankyou", sizeof(q->sound_thanks) - 1);
2179                                 strncpy(q->sound_lessthan, "queue-less-than", sizeof(q->sound_lessthan) - 1);
2180                                 strncpy(q->sound_reporthold, "queue-reporthold", sizeof(q->sound_reporthold) - 1);
2181                                 prev = q->members;
2182                                 if (prev) {
2183                                         /* find the end of any dynamic members */
2184                                         while(prev->next)
2185                                                 prev = prev->next;
2186                                 }
2187                                 var = ast_variable_browse(cfg, cat);
2188                                 while(var) {
2189                                         if (!strcasecmp(var->name, "member")) {
2190                                                 /* Add a new member */
2191                                                 cur = malloc(sizeof(struct member));
2192                                                 if (cur) {
2193                                                         memset(cur, 0, sizeof(struct member));
2194                                                         strncpy(cur->interface, var->value, sizeof(cur->interface) - 1);
2195                                                         if ((tmp = strchr(cur->interface, ','))) {
2196                                                                 *tmp = '\0';
2197                                                                 tmp++;
2198                                                                 cur->penalty = atoi(tmp);
2199                                                                 if (cur->penalty < 0)
2200                                                                         cur->penalty = 0;
2201                                                         }
2202                                                         if (!strchr(cur->interface, '/'))
2203                                                                 ast_log(LOG_WARNING, "No location at line %d of queue.conf\n", var->lineno);
2204                                                         if (prev)
2205                                                                 prev->next = cur;
2206                                                         else
2207                                                                 q->members = cur;
2208                                                         prev = cur;
2209                                                 }
2210                                         } else if (!strcasecmp(var->name, "music")) {
2211                                                 strncpy(q->moh, var->value, sizeof(q->moh) - 1);
2212                                         } else if (!strcasecmp(var->name, "announce")) {
2213                                                 strncpy(q->announce, var->value, sizeof(q->announce) - 1);
2214                                         } else if (!strcasecmp(var->name, "context")) {
2215                                                 strncpy(q->context, var->value, sizeof(q->context) - 1);
2216                                         } else if (!strcasecmp(var->name, "timeout")) {
2217                                                 q->timeout = atoi(var->value);
2218                                         } else if (!strcasecmp(var->name, "monitor-join")) {
2219                                                 q->monjoin = ast_true(var->value);
2220                                         } else if (!strcasecmp(var->name, "monitor-format")) {
2221                                                 strncpy(q->monfmt, var->value, sizeof(q->monfmt) - 1);
2222                                         } else if (!strcasecmp(var->name, "queue-youarenext")) {
2223                                                 strncpy(q->sound_next, var->value, sizeof(q->sound_next) - 1);
2224                                         } else if (!strcasecmp(var->name, "queue-thereare")) {
2225                                                 strncpy(q->sound_thereare, var->value, sizeof(q->sound_thereare) - 1);
2226                                         } else if (!strcasecmp(var->name, "queue-callswaiting")) {
2227                                                 strncpy(q->sound_calls, var->value, sizeof(q->sound_calls) - 1);
2228                                         } else if (!strcasecmp(var->name, "queue-holdtime")) {
2229                                                 strncpy(q->sound_holdtime, var->value, sizeof(q->sound_holdtime) - 1);
2230                                         } else if (!strcasecmp(var->name, "queue-minutes")) {
2231                                                 strncpy(q->sound_minutes, var->value, sizeof(q->sound_minutes) - 1);
2232                                         } else if (!strcasecmp(var->name, "queue-seconds")) {
2233                                                 strncpy(q->sound_seconds, var->value, sizeof(q->sound_seconds) - 1);
2234                                         } else if (!strcasecmp(var->name, "queue-lessthan")) {
2235                                                 strncpy(q->sound_lessthan, var->value, sizeof(q->sound_lessthan) - 1);
2236                                         } else if (!strcasecmp(var->name, "queue-thankyou")) {
2237                                                 strncpy(q->sound_thanks, var->value, sizeof(q->sound_thanks) - 1);
2238                                         } else if (!strcasecmp(var->name, "queue-reporthold")) {
2239                                                 strncpy(q->sound_reporthold, var->value, sizeof(q->sound_reporthold) - 1);
2240                                         } else if (!strcasecmp(var->name, "announce-frequency")) {
2241                                                 q->announcefrequency = atoi(var->value);
2242                                         } else if (!strcasecmp(var->name, "announce-round-seconds")) {
2243                                                 q->roundingseconds = atoi(var->value);
2244                                                 if(q->roundingseconds>60 || q->roundingseconds<0) {
2245                                                         ast_log(LOG_WARNING, "'%s' isn't a valid value for queue-rounding-seconds using 0 instead at line %d of queue.conf\n", var->value, var->lineno);
2246                                                         q->roundingseconds=0;
2247                                                 }
2248                                         } else if (!strcasecmp(var->name, "announce-holdtime")) {
2249                                                 q->announceholdtime = (!strcasecmp(var->value,"once")) ? 1 : ast_true(var->value);
2250                                         } else if (!strcasecmp(var->name, "retry")) {
2251                                                 q->retry = atoi(var->value);
2252                                         } else if (!strcasecmp(var->name, "wrapuptime")) {
2253                                                 q->wrapuptime = atoi(var->value);
2254                                         } else if (!strcasecmp(var->name, "maxlen")) {
2255                                                 q->maxlen = atoi(var->value);
2256                                         } else if (!strcasecmp(var->name, "servicelevel")) {
2257                                                 q->servicelevel= atoi(var->value);
2258                                         } else if (!strcasecmp(var->name, "strategy")) {
2259                                                 q->strategy = strat2int(var->value);
2260                                                 if (q->strategy < 0) {
2261                                                         ast_log(LOG_WARNING, "'%s' isn't a valid strategy, using ringall instead\n", var->value);
2262                                                         q->strategy = 0;
2263                                                 }
2264                                         } else if (!strcasecmp(var->name, "joinempty")) {
2265                                                 q->joinempty = ast_true(var->value);
2266                                         } else if (!strcasecmp(var->name, "leavewhenempty")) {
2267                                                 q->leavewhenempty = ast_true(var->value);
2268                                         } else if (!strcasecmp(var->name, "eventwhencalled")) {
2269                                                 q->eventwhencalled = ast_true(var->value);
2270                                         } else if (!strcasecmp(var->name, "reportholdtime")) {
2271                                                 q->reportholdtime = ast_true(var->value);
2272                                         } else if (!strcasecmp(var->name, "memberdelay")) {
2273                                                 q->memberdelay = atoi(var->value);
2274                                         } else {
2275                                                 ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queue.conf\n", cat, var->name, var->lineno);
2276                                         }
2277                                         var = var->next;
2278                                 }
2279                                 if (q->retry < 1)
2280                                         q->retry = DEFAULT_RETRY;
2281                                 if (q->timeout < 0)
2282                                         q->timeout = DEFAULT_TIMEOUT;
2283                                 if (q->maxlen < 0)
2284                                         q->maxlen = 0;
2285                                 if (!new) 
2286                                         ast_mutex_unlock(&q->lock);
2287                                 if (new) {
2288                                         q->next = queues;
2289                                         queues = q;
2290                                 }
2291                         }
2292                 } else {
2293                         /* Initialize global settings */
2294                         queue_persistent_members = 0;
2295                         if ((general_val = ast_variable_retrieve(cfg, "general", "persistentmembers")))
2296                             queue_persistent_members = ast_true(general_val);
2297                 }
2298                 cat = ast_category_browse(cfg, cat);
2299         }
2300         ast_destroy(cfg);
2301         q = queues;
2302         ql = NULL;
2303         while(q) {
2304                 qn = q->next;
2305                 if (q->dead) {
2306                         if (ql)
2307                                 ql->next = q->next;
2308                         else
2309                                 queues = q->next;
2310                         if (!q->count) {
2311                                 free(q);
2312                         } else
2313                                 ast_log(LOG_WARNING, "XXX Leaking a little memory :( XXX\n");
2314                 } else {
2315                         for (cur = q->members; cur; cur = cur->next)
2316                                 cur->status = ast_device_state(cur->interface);
2317                         ql = q;
2318                 }
2319                 q = qn;
2320         }
2321         ast_mutex_unlock(&qlock);
2322 }
2323
2324 static char *status2str(int status, char *buf, int buflen)
2325 {
2326         switch(status) {
2327         case AST_DEVICE_UNKNOWN:
2328                 strncpy(buf, "unknown", buflen - 1);
2329                 break;
2330         case AST_DEVICE_NOT_INUSE:
2331                 strncpy(buf, "notinuse", buflen - 1);
2332                 break;
2333         case AST_DEVICE_INUSE:
2334                 strncpy(buf, "inuse", buflen - 1);
2335                 break;
2336         case AST_DEVICE_BUSY:
2337                 strncpy(buf, "busy", buflen - 1);
2338                 break;
2339         case AST_DEVICE_INVALID:
2340                 strncpy(buf, "invalid", buflen - 1);
2341                 break;
2342         case AST_DEVICE_UNAVAILABLE:
2343                 strncpy(buf, "unavailable", buflen - 1);
2344                 break;
2345         default:
2346                 snprintf(buf, buflen, "unknown status %d", status);
2347         }
2348         return buf;
2349 }
2350
2351 static int __queues_show(int fd, int argc, char **argv, int queue_show)
2352 {
2353         struct ast_call_queue *q;
2354         struct queue_ent *qe;
2355         struct member *mem;
2356         int pos;
2357         time_t now;
2358         char max[80] = "";
2359         char calls[80] = "";
2360         char tmpbuf[80] = "";
2361         float sl = 0;
2362
2363         time(&now);
2364         if ((!queue_show && argc != 2) || (queue_show && argc != 3))
2365                 return RESULT_SHOWUSAGE;
2366         ast_mutex_lock(&qlock);
2367         q = queues;
2368         if (!q) {       
2369                 ast_mutex_unlock(&qlock);
2370                 if (queue_show)
2371                         ast_cli(fd, "No such queue: %s.\n",argv[2]);
2372                 else
2373                         ast_cli(fd, "No queues.\n");
2374                 return RESULT_SUCCESS;
2375         }
2376         while(q) {
2377                 ast_mutex_lock(&q->lock);
2378                 if (queue_show) {
2379                         if (strcasecmp(q->name, argv[2]) != 0) {
2380                                 ast_mutex_unlock(&q->lock);
2381                                 q = q->next;
2382                                 if (!q) {
2383                                         ast_cli(fd, "No such queue: %s.\n",argv[2]);
2384                                         break;
2385                                 }
2386                                 continue;
2387                         }
2388                 }
2389                 if (q->maxlen)
2390                         snprintf(max, sizeof(max), "%d", q->maxlen);
2391                 else
2392                         strncpy(max, "unlimited", sizeof(max) - 1);
2393                 sl = 0;
2394                 if(q->callscompleted > 0)
2395                         sl = 100*((float)q->callscompletedinsl/(float)q->callscompleted);
2396                 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",
2397                         q->name, q->count, max, int2strat(q->strategy), q->holdtime, q->callscompleted, q->callsabandoned,sl,q->servicelevel);
2398                 if (q->members) {
2399                         ast_cli(fd, "   Members: \n");
2400                         for (mem = q->members; mem; mem = mem->next) {
2401                                 if (mem->penalty)
2402                                         snprintf(max, sizeof(max) - 20, " with penalty %d", mem->penalty);
2403                                 else
2404                                         max[0] = '\0';
2405                                 if (mem->dynamic)
2406                                         strncat(max, " (dynamic)", sizeof(max) - strlen(max) - 1);
2407                                 if (mem->status)
2408                                         snprintf(max + strlen(max), sizeof(max) - strlen(max), " (%s)", status2str(mem->status, tmpbuf, sizeof(tmpbuf)));
2409                                 if (mem->calls) {
2410                                         snprintf(calls, sizeof(calls), " has taken %d calls (last was %ld secs ago)",
2411                                                         mem->calls, (long)(time(NULL) - mem->lastcall));
2412                                 } else
2413                                         strncpy(calls, " has taken no calls yet", sizeof(calls) - 1);
2414                                 ast_cli(fd, "      %s%s%s\n", mem->interface, max, calls);
2415                         }
2416                 } else
2417                         ast_cli(fd, "   No Members\n");
2418                 if (q->head) {
2419                         pos = 1;
2420                         ast_cli(fd, "   Callers: \n");
2421                         for (qe = q->head; qe; qe = qe->next) 
2422                                 ast_cli(fd, "      %d. %s (wait: %ld:%2.2ld, prio: %d)\n", pos++, qe->chan->name,
2423                                                                 (long)(now - qe->start) / 60, (long)(now - qe->start) % 60, qe->prio);
2424                 } else
2425                         ast_cli(fd, "   No Callers\n");
2426                 ast_cli(fd, "\n");
2427                 ast_mutex_unlock(&q->lock);
2428                 q = q->next;
2429                 if (queue_show)
2430                         break;
2431         }
2432         ast_mutex_unlock(&qlock);
2433         return RESULT_SUCCESS;
2434 }
2435
2436 static int queues_show(int fd, int argc, char **argv)
2437 {
2438         return __queues_show(fd, argc, argv, 0);
2439 }
2440
2441 static int queue_show(int fd, int argc, char **argv)
2442 {
2443         return __queues_show(fd, argc, argv, 1);
2444 }
2445
2446 static char *complete_queue(char *line, char *word, int pos, int state)
2447 {
2448         struct ast_call_queue *q;
2449         int which=0;
2450         
2451         ast_mutex_lock(&qlock);
2452         for (q = queues; q; q = q->next) {
2453                 if (!strncasecmp(word, q->name, strlen(word))) {
2454                         if (++which > state)
2455                                 break;
2456                 }
2457         }
2458         ast_mutex_unlock(&qlock);
2459         return q ? strdup(q->name) : NULL;
2460 }
2461
2462 /* JDG: callback to display queues status in manager */
2463 static int manager_queues_show( struct mansession *s, struct message *m )
2464 {
2465         char *a[] = { "show", "queues" };
2466         return queues_show( s->fd, 2, a );
2467 } /* /JDG */
2468
2469
2470 /* Dump queue status */
2471 static int manager_queues_status( struct mansession *s, struct message *m )
2472 {
2473         time_t now;
2474         int pos;
2475         char *id = astman_get_header(m,"ActionID");
2476         char idText[256] = "";
2477         struct ast_call_queue *q;
2478         struct queue_ent *qe;
2479         float sl = 0;
2480         struct member *mem;
2481         astman_send_ack(s, m, "Queue status will follow");
2482         time(&now);
2483         ast_mutex_lock(&qlock);
2484         if (!ast_strlen_zero(id)) {
2485                 snprintf(idText,256,"ActionID: %s\r\n",id);
2486         }
2487         for (q = queues; q; q = q->next) {
2488                 ast_mutex_lock(&q->lock);
2489
2490                 /* List queue properties */
2491                 if(q->callscompleted > 0)
2492                         sl = 100*((float)q->callscompletedinsl/(float)q->callscompleted);
2493                 ast_mutex_lock(&s->lock);
2494                 ast_cli(s->fd, "Event: QueueParams\r\n"
2495                                         "Queue: %s\r\n"
2496                                         "Max: %d\r\n"
2497                                         "Calls: %d\r\n"
2498                                         "Holdtime: %d\r\n"
2499                                         "Completed: %d\r\n"
2500                                         "Abandoned: %d\r\n"
2501                                         "ServiceLevel: %d\r\n"
2502                                         "ServicelevelPerf: %2.1f\r\n"
2503                                         "%s"
2504                                         "\r\n",
2505                                                 q->name, q->maxlen, q->count, q->holdtime, q->callscompleted,
2506                                                 q->callsabandoned, q->servicelevel, sl, idText);
2507
2508                 /* List Queue Members */
2509                 for (mem = q->members; mem; mem = mem->next) 
2510                         ast_cli(s->fd, "Event: QueueMember\r\n"
2511                                 "Queue: %s\r\n"
2512                                 "Location: %s\r\n"
2513                                 "Membership: %s\r\n"
2514                                 "Penalty: %d\r\n"
2515                                 "CallsTaken: %d\r\n"
2516                                 "LastCall: %ld\r\n"
2517                                 "Status: %d\r\n"
2518                                 "%s"
2519                                 "\r\n",
2520                                         q->name, mem->interface, mem->dynamic ? "dynamic" : "static",
2521                                         mem->penalty, mem->calls, mem->lastcall, mem->status, idText);
2522
2523                 /* List Queue Entries */
2524
2525                 pos = 1;
2526                 for (qe = q->head; qe; qe = qe->next) 
2527                         ast_cli(s->fd, "Event: QueueEntry\r\n"
2528                                 "Queue: %s\r\n"
2529                                 "Position: %d\r\n"
2530                                 "Channel: %s\r\n"
2531                                 "CallerID: %s\r\n"
2532                                 "CallerIDName: %s\r\n"
2533                                 "Wait: %ld\r\n"
2534                                 "%s"
2535                                 "\r\n", 
2536                                         q->name, pos++, qe->chan->name, 
2537                                         qe->chan->cid.cid_num ? qe->chan->cid.cid_num : "unknown",
2538                                         qe->chan->cid.cid_name ? qe->chan->cid.cid_name : "unknown",
2539                                         (long)(now - qe->start), idText);
2540                 ast_mutex_unlock(&s->lock);
2541                 ast_mutex_unlock(&q->lock);
2542         }
2543         ast_mutex_unlock(&qlock);
2544         return RESULT_SUCCESS;
2545 }
2546
2547 static int manager_add_queue_member(struct mansession *s, struct message *m)
2548 {
2549         char *queuename, *interface, *penalty_s;
2550         int penalty = 0;
2551
2552         queuename = astman_get_header(m, "Queue");
2553         interface = astman_get_header(m, "Interface");
2554         penalty_s = astman_get_header(m, "Penalty");
2555
2556         if (ast_strlen_zero(queuename)) {
2557                 astman_send_error(s, m, "'Queue' not specified.");
2558                 return 0;
2559         }
2560
2561         if (ast_strlen_zero(interface)) {
2562                 astman_send_error(s, m, "'Interface' not specified.");
2563                 return 0;
2564         }
2565
2566         if (ast_strlen_zero(penalty_s))
2567                 penalty = 0;
2568         else if (sscanf(penalty_s, "%d", &penalty) != 1) {
2569                 penalty = 0;
2570         }
2571
2572         switch (add_to_queue(queuename, interface, penalty)) {
2573         case RES_OKAY:
2574                 astman_send_ack(s, m, "Added interface to queue");
2575                 break;
2576         case RES_EXISTS:
2577                 astman_send_error(s, m, "Unable to add interface: Already there");
2578                 break;
2579         case RES_NOSUCHQUEUE:
2580                 astman_send_error(s, m, "Unable to add interface to queue: No such queue");
2581                 break;
2582         case RES_OUTOFMEMORY:
2583                 astman_send_error(s, m, "Out of memory");
2584                 break;
2585         }
2586         return 0;
2587 }
2588
2589 static int manager_remove_queue_member(struct mansession *s, struct message *m)
2590 {
2591         char *queuename, *interface;
2592
2593         queuename = astman_get_header(m, "Queue");
2594         interface = astman_get_header(m, "Interface");
2595
2596         if (ast_strlen_zero(queuename) || ast_strlen_zero(interface)) {
2597                 astman_send_error(s, m, "Need 'Queue' and 'Interface' parameters.");
2598                 return 0;
2599         }
2600
2601         switch (remove_from_queue(queuename, interface)) {
2602         case RES_OKAY:
2603                 astman_send_ack(s, m, "Removed interface from queue");
2604                 break;
2605         case RES_EXISTS:
2606                 astman_send_error(s, m, "Unable to remove interface: Not there");
2607                 break;
2608         case RES_NOSUCHQUEUE:
2609                 astman_send_error(s, m, "Unable to remove interface from queue: No such queue");
2610                 break;
2611         case RES_OUTOFMEMORY:
2612                 astman_send_error(s, m, "Out of memory");
2613                 break;
2614         }
2615         return 0;
2616 }
2617
2618 static int handle_add_queue_member(int fd, int argc, char *argv[])
2619 {
2620         char *queuename, *interface;
2621         int penalty;
2622
2623         if ((argc != 6) && (argc != 8)) {
2624                 return RESULT_SHOWUSAGE;
2625         } else if (strcmp(argv[4], "to")) {
2626                 return RESULT_SHOWUSAGE;
2627         } else if ((argc == 8) && strcmp(argv[6], "penalty")) {
2628                 return RESULT_SHOWUSAGE;
2629         }
2630
2631         queuename = argv[5];
2632         interface = argv[3];
2633         if (argc == 8) {
2634                 if (sscanf(argv[7], "%d", &penalty) == 1) {
2635                         if (penalty < 0) {
2636                                 ast_cli(fd, "Penalty must be >= 0\n");
2637                                 penalty = 0;
2638                         }
2639                 } else {
2640                         ast_cli(fd, "Penalty must be an integer >= 0\n");
2641                         penalty = 0;
2642                 }
2643         } else {
2644                 penalty = 0;
2645         }
2646
2647         switch (add_to_queue(queuename, interface, penalty)) {
2648         case RES_OKAY:
2649                 ast_cli(fd, "Added interface '%s' to queue '%s'\n", interface, queuename);
2650                 return RESULT_SUCCESS;
2651         case RES_EXISTS:
2652                 ast_cli(fd, "Unable to add interface '%s' to queue '%s': Already there\n", interface, queuename);
2653                 return RESULT_FAILURE;
2654         case RES_NOSUCHQUEUE:
2655                 ast_cli(fd, "Unable to add interface to queue '%s': No such queue\n", queuename);
2656                 return RESULT_FAILURE;
2657         case RES_OUTOFMEMORY:
2658                 ast_cli(fd, "Out of memory\n");
2659                 return RESULT_FAILURE;
2660         default:
2661                 return RESULT_FAILURE;
2662         }
2663 }
2664
2665 static char *complete_add_queue_member(char *line, char *word, int pos, int state)
2666 {
2667         /* 0 - add; 1 - queue; 2 - member; 3 - <member>; 4 - to; 5 - <queue>; 6 - penalty; 7 - <penalty> */
2668         switch (pos) {
2669         case 3:
2670                 /* Don't attempt to complete name of member (infinite possibilities) */
2671                 return NULL;
2672         case 4:
2673                 if (state == 0) {
2674                         return strdup("to");
2675                 } else {
2676                         return NULL;
2677                 }
2678         case 5:
2679                 /* No need to duplicate code */
2680                 return complete_queue(line, word, pos, state);
2681         case 6:
2682                 if (state == 0) {
2683                         return strdup("penalty");
2684                 } else {
2685                         return NULL;
2686                 }
2687         case 7:
2688                 if (state < 100) {      /* 0-99 */
2689                         char *num = malloc(3);
2690                         if (num) {
2691                                 sprintf(num, "%d", state);
2692                         }
2693                         return num;
2694                 } else {
2695                         return NULL;
2696                 }
2697         default:
2698                 return NULL;
2699         }
2700 }
2701
2702 static int handle_remove_queue_member(int fd, int argc, char *argv[])
2703 {
2704         char *queuename, *interface;
2705
2706         if (argc != 6) {
2707                 return RESULT_SHOWUSAGE;
2708         } else if (strcmp(argv[4], "from")) {
2709                 return RESULT_SHOWUSAGE;
2710         }
2711
2712         queuename = argv[5];
2713         interface = argv[3];
2714
2715         switch (remove_from_queue(queuename, interface)) {
2716         case RES_OKAY:
2717                 ast_cli(fd, "Removed interface '%s' from queue '%s'\n", interface, queuename);
2718                 return RESULT_SUCCESS;
2719         case RES_EXISTS:
2720                 ast_cli(fd, "Unable to remove interface '%s' from queue '%s': Not there\n", interface, queuename);
2721                 return RESULT_FAILURE;
2722         case RES_NOSUCHQUEUE:
2723                 ast_cli(fd, "Unable to remove interface from queue '%s': No such queue\n", queuename);
2724                 return RESULT_FAILURE;
2725         case RES_OUTOFMEMORY:
2726                 ast_cli(fd, "Out of memory\n");
2727                 return RESULT_FAILURE;
2728         default:
2729                 return RESULT_FAILURE;
2730         }
2731 }
2732
2733 static char *complete_remove_queue_member(char *line, char *word, int pos, int state)
2734 {
2735         int which = 0;
2736         struct ast_call_queue *q;
2737         struct member *m;
2738
2739         /* 0 - add; 1 - queue; 2 - member; 3 - <member>; 4 - to; 5 - <queue> */
2740         if ((pos > 5) || (pos < 3)) {
2741                 return NULL;
2742         }
2743         if (pos == 4) {
2744                 if (state == 0) {
2745                         return strdup("from");
2746                 } else {
2747                         return NULL;
2748                 }
2749         }
2750
2751         if (pos == 5) {
2752                 /* No need to duplicate code */
2753                 return complete_queue(line, word, pos, state);
2754         }
2755
2756         if (queues != NULL) {
2757                 for (q = queues ; q ; q = q->next) {
2758                         ast_mutex_lock(&q->lock);
2759                         for (m = q->members ; m ; m = m->next) {
2760                                 if (++which > state) {
2761                                         ast_mutex_unlock(&q->lock);
2762                                         return strdup(m->interface);
2763                                 }
2764                         }
2765                         ast_mutex_unlock(&q->lock);
2766                 }
2767         }
2768         return NULL;
2769 }
2770
2771 static char show_queues_usage[] = 
2772 "Usage: show queues\n"
2773 "       Provides summary information on call queues.\n";
2774
2775 static struct ast_cli_entry cli_show_queues = {
2776         { "show", "queues", NULL }, queues_show, 
2777         "Show status of queues", show_queues_usage, NULL };
2778
2779 static char show_queue_usage[] = 
2780 "Usage: show queue\n"
2781 "       Provides summary information on a specified queue.\n";
2782
2783 static struct ast_cli_entry cli_show_queue = {
2784         { "show", "queue", NULL }, queue_show, 
2785         "Show status of a specified queue", show_queue_usage, complete_queue };
2786
2787 static char aqm_cmd_usage[] =
2788 "Usage: add queue member <channel> to <queue> [penalty <penalty>]\n";
2789
2790 static struct ast_cli_entry cli_add_queue_member = {