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