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