2 * Asterisk -- A telephony toolkit for Linux.
4 * True call queues with optional send URL on answer
6 * Copyright (C) 1999-2004, Digium, Inc.
8 * Mark Spencer <markster@digium.com>
10 * 2004-11-25: Persistent Dynamic Members added by:
11 * NetNation Communications (www.netnation.com)
12 * Kevin Lindsay <kevinl@netnation.com>
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.
20 * 2004-06-04: Priorities in queues added by inAccess Networks (work funded by Hellas On Line (HOL) www.hol.gr).
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
30 * Patch Version 1.07 2003-12-24 01
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>
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>
38 * This program is free software, distributed under the terms of
39 * the GNU General Public License
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>
67 #include <sys/signal.h>
68 #include <netinet/in.h>
70 #include "../astconf.h"
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
79 static struct strategy {
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" },
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 */
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 */
100 static char *tdesc = "True Call Queueing";
102 static char *app = "Queue";
104 static char *synopsis = "Queue a call for a call queue";
106 static char *descrip =
107 " Queue(queuename[|options[|URL][|announceoverride][|timeout]]):\n"
108 "Queues an incoming call in a particular call queue as defined in queues.conf.\n"
109 " This application returns -1 if the originating channel hangs up, or if the\n"
110 "call is bridged and either of the parties in the bridge terminate the call.\n"
111 "Returns 0 if the queue is full, nonexistant, or has no members.\n"
112 "The option string may contain zero or more of the following characters:\n"
113 " 't' -- allow the called user transfer the calling user\n"
114 " 'T' -- to allow the calling user to transfer the call.\n"
115 " 'd' -- data-quality (modem) call (minimum delay).\n"
116 " 'h' -- allow callee to hang up by hitting *.\n"
117 " 'H' -- allow caller to hang up by hitting *.\n"
118 " 'n' -- no retries on the timeout; will exit this application and \n"
119 " go to the next step.\n"
120 " 'r' -- ring instead of playing MOH\n"
121 " In addition to transferring the call, a call may be parked and then picked\n"
122 "up by another user.\n"
123 " The optional URL will be sent to the called party if the channel supports\n"
125 " The timeout will cause the queue to fail out after a specified number of\n"
126 "seconds, checked between each queues.conf 'timeout' and 'retry' cycle.\n";
129 static char *app_aqm = "AddQueueMember" ;
130 static char *app_aqm_synopsis = "Dynamically adds queue members" ;
131 static char *app_aqm_descrip =
132 " AddQueueMember(queuename[|interface[|penalty]]):\n"
133 "Dynamically adds interface to an existing queue.\n"
134 "If the interface is already in the queue and there exists an n+101 priority\n"
135 "then it will then jump to this priority. Otherwise it will return an error\n"
136 "Returns -1 if there is an error.\n"
137 "Example: AddQueueMember(techsupport|SIP/3000)\n"
140 static char *app_rqm = "RemoveQueueMember" ;
141 static char *app_rqm_synopsis = "Dynamically removes queue members" ;
142 static char *app_rqm_descrip =
143 " RemoveQueueMember(queuename[|interface]):\n"
144 "Dynamically removes interface to an existing queue\n"
145 "If the interface is NOT in the queue and there exists an n+101 priority\n"
146 "then it will then jump to this priority. Otherwise it will return an error\n"
147 "Returns -1 if there is an error.\n"
148 "Example: RemoveQueueMember(techsupport|SIP/3000)\n"
151 /* Persistent Members astdb family */
152 static const char *pm_family = "/Queue/PersistentMembers";
153 /* The maximum lengh of each persistent member queue database entry */
154 #define PM_MAX_LEN 2048
155 /* queues.conf [general] option */
156 static int queue_persistent_members = 0;
158 #define QUEUE_FLAG_RINGBACKONLY (1 << 0)
159 #define QUEUE_FLAG_MUSICONHOLD (1 << 1)
160 #define QUEUE_FLAG_DATAQUALITY (1 << 2)
161 #define QUEUE_FLAG_REDIR_IN (1 << 3)
162 #define QUEUE_FLAG_REDIR_OUT (1 << 4)
163 #define QUEUE_FLAG_DISCON_IN (1 << 5)
164 #define QUEUE_FLAG_DISCON_OUT (1 << 6)
165 #define QUEUE_FLAG_MONJOIN (1 << 7) /* Should we join the two files when we are done with the call */
166 #define QUEUE_FLAG_DEAD (1 << 8) /* Whether the queue is dead or not */
167 #define QUEUE_FLAG_JOINEMPTY (1 << 9) /* Do we care if the queue has no members? */
168 #define QUEUE_FLAG_EVENTWHENCALLED (1 << 10) /* Generate an event when the agent is called (before pickup) */
169 #define QUEUE_FLAG_LEAVEWHENEMPTY (1 << 11) /* If all agents leave the queue, remove callers from the queue */
170 #define QUEUE_FLAG_REPORTHOLDTIME (1 << 12) /* Should we report caller hold time to answering member? */
171 #define QUEUE_FLAG_WRAPPED (1 << 13) /* Round Robin - wrapped around? */
173 /* We define a custom "local user" structure because we
174 use it not only for keeping track of what is in use but
175 also for keeping track of who we're dialing. */
178 struct ast_channel *chan;
183 int flags; /* flag bits */
185 struct member *member;
186 struct localuser *next;
192 struct ast_call_queue *parent; /* What queue is our parent */
193 char moh[80]; /* Name of musiconhold to be used */
194 char announce[80]; /* Announcement to play for member when call is answered */
195 char context[80]; /* Context when user exits queue */
196 int pos; /* Where we are in the queue */
197 int prio; /* Our priority */
198 int last_pos_said; /* Last position we told the user */
199 time_t last_pos; /* Last time we told the user their position */
200 int opos; /* Where we started in the queue */
201 int handled; /* Whether our call was handled */
202 time_t start; /* When we started holding */
203 time_t expire; /* When this entry should expire (time out of queue) */
204 struct ast_channel *chan; /* Our channel */
205 struct queue_ent *next; /* The next queue entry */
209 char interface[80]; /* Technology/Location */
210 int penalty; /* Are we a last resort? */
211 int calls; /* Number of calls serviced by this member */
212 int dynamic; /* Are we dynamically added? */
213 int status; /* Status of queue member */
214 time_t lastcall; /* When last successful call was hungup */
215 struct member *next; /* Next member */
218 struct ast_call_queue {
220 char name[80]; /* Name of the queue */
221 char moh[80]; /* Name of musiconhold to be used */
222 char announce[80]; /* Announcement to play when call is answered */
223 char context[80]; /* Context for this queue */
224 int flags; /* flag bits */
225 int strategy; /* Queueing strategy */
226 int announcefrequency; /* How often to announce their position */
227 int roundingseconds; /* How many seconds do we round to? */
228 int announceholdtime; /* When to announce holdtime: 0 = never, -1 = every announcement, 1 = only once */
229 int holdtime; /* Current avg holdtime for this queue, based on recursive boxcar filter */
230 int callscompleted; /* Number of queue calls completed */
231 int callsabandoned; /* Number of queue calls abandoned */
232 int servicelevel; /* seconds setting for servicelevel*/
233 int callscompletedinsl; /* Number of queue calls answered with servicelevel*/
234 char monfmt[8]; /* Format to use when recording calls */
235 char sound_next[80]; /* Sound file: "Your call is now first in line" (def. queue-youarenext) */
236 char sound_thereare[80]; /* Sound file: "There are currently" (def. queue-thereare) */
237 char sound_calls[80]; /* Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting)*/
238 char sound_holdtime[80]; /* Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
239 char sound_minutes[80]; /* Sound file: "minutes." (def. queue-minutes) */
240 char sound_lessthan[80]; /* Sound file: "less-than" (def. queue-lessthan) */
241 char sound_seconds[80]; /* Sound file: "seconds." (def. queue-seconds) */
242 char sound_thanks[80]; /* Sound file: "Thank you for your patience." (def. queue-thankyou) */
243 char sound_reporthold[80]; /* Sound file: "Hold time" (def. queue-reporthold) */
245 int count; /* How many entries are in the queue */
246 int maxlen; /* Max number of entries in queue */
247 int wrapuptime; /* Wrapup Time */
249 int retry; /* Retry calling everyone after this amount of time */
250 int timeout; /* How long to wait for an answer */
252 /* Queue strategy things */
253 int rrpos; /* Round Robin - position */
254 int memberdelay; /* Seconds to delay connecting member to caller */
256 struct member *members; /* Member channels to be tried */
257 struct queue_ent *head; /* Start of the actual queue */
258 struct ast_call_queue *next; /* Next call queue */
261 static struct ast_call_queue *queues = NULL;
262 AST_MUTEX_DEFINE_STATIC(qlock);
265 static char *int2strat(int strategy)
268 for (x=0;x<sizeof(strategies) / sizeof(strategies[0]);x++) {
269 if (strategy == strategies[x].strategy)
270 return strategies[x].name;
275 static int strat2int(char *strategy)
278 for (x=0;x<sizeof(strategies) / sizeof(strategies[0]);x++) {
279 if (!strcasecmp(strategy, strategies[x].name))
280 return strategies[x].strategy;
285 /* Insert the 'new' entry after the 'prev' entry of queue 'q' */
286 static inline void insert_entry(struct ast_call_queue *q,
287 struct queue_ent *prev, struct queue_ent *new, int *pos)
289 struct queue_ent *cur;
306 static int has_no_members(struct ast_call_queue *q)
308 struct member *member;
311 while(empty && member) {
312 switch(member->status) {
313 case AST_DEVICE_UNAVAILABLE:
314 case AST_DEVICE_INVALID:
315 /* Not logged on, etc */
321 member = member->next;
331 static void *changethread(void *data)
333 struct ast_call_queue *q;
334 struct statechange *sc = data;
338 loc = strchr(sc->dev, '/');
343 ast_log(LOG_WARNING, "Can't change device '%s' with no technology!\n", sc->dev);
348 ast_log(LOG_DEBUG, "Device '%s/%s' changed to state '%d'\n", sc->dev, loc, sc->state);
349 ast_mutex_lock(&qlock);
350 for (q = queues; q; q = q->next) {
351 ast_mutex_lock(&q->lock);
354 if (!strcasecmp(sc->dev, cur->interface)) {
355 if (cur->status != sc->state) {
356 cur->status = sc->state;
357 manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
365 q->name, cur->interface, cur->dynamic ? "dynamic" : "static",
366 cur->penalty, cur->calls, cur->lastcall, cur->status);
371 ast_mutex_unlock(&q->lock);
373 ast_mutex_unlock(&qlock);
375 ast_log(LOG_DEBUG, "Device '%s/%s' changed to state '%d'\n", sc->dev, loc, sc->state);
380 static int statechange_queue(const char *dev, int state, void *ign)
382 /* Avoid potential for deadlocks by spawning a new thread to handle
384 struct statechange *sc;
388 sc = malloc(sizeof(struct statechange) + strlen(dev) + 1);
391 strcpy(sc->dev, dev);
392 pthread_attr_init(&attr);
393 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
394 if (ast_pthread_create(&t, &attr, changethread, sc)) {
395 ast_log(LOG_WARNING, "Failed to create update thread!\n");
402 static int join_queue(char *queuename, struct queue_ent *qe)
404 struct ast_call_queue *q;
405 struct queue_ent *cur, *prev = NULL;
410 ast_mutex_lock(&qlock);
411 for (q = queues; q; q = q->next) {
412 if (!strcasecmp(q->name, queuename)) {
413 /* This is our one */
414 ast_mutex_lock(&q->lock);
415 if ((!has_no_members(q) || ast_test_flag(q, QUEUE_FLAG_JOINEMPTY)) && (!q->maxlen || (q->count < q->maxlen))) {
416 /* There's space for us, put us at the right position inside
418 * Take into account the priority of the calling user */
423 /* We have higher priority than the current user, enter
424 * before him, after all the other users with priority
425 * higher or equal to our priority. */
426 if ((!inserted) && (qe->prio > cur->prio)) {
427 insert_entry(q, prev, qe, &pos);
434 /* No luck, join at the end of the queue */
436 insert_entry(q, prev, qe, &pos);
437 strncpy(qe->moh, q->moh, sizeof(qe->moh) - 1);
438 strncpy(qe->announce, q->announce, sizeof(qe->announce) - 1);
439 strncpy(qe->context, q->context, sizeof(qe->context) - 1);
442 manager_event(EVENT_FLAG_CALL, "Join",
443 "Channel: %s\r\nCallerID: %s\r\nCallerIDName: %s\r\nQueue: %s\r\nPosition: %d\r\nCount: %d\r\n",
445 qe->chan->cid.cid_num ? qe->chan->cid.cid_num : "unknown",
446 qe->chan->cid.cid_name ? qe->chan->cid.cid_name : "unknown",
447 q->name, qe->pos, q->count );
449 ast_log(LOG_NOTICE, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, qe->chan->name, qe->pos );
452 ast_mutex_unlock(&q->lock);
456 ast_mutex_unlock(&qlock);
460 static void free_members(struct ast_call_queue *q, int all)
462 /* Free non-dynamic members */
463 struct member *curm, *next, *prev;
468 if (all || !curm->dynamic) {
480 static void destroy_queue(struct ast_call_queue *q)
482 struct ast_call_queue *cur, *prev = NULL;
483 ast_mutex_lock(&qlock);
484 for (cur = queues; cur; cur = cur->next) {
487 prev->next = cur->next;
494 ast_mutex_unlock(&qlock);
496 ast_mutex_destroy(&q->lock);
500 static int play_file(struct ast_channel *chan, char *filename)
504 ast_stopstream(chan);
505 res = ast_streamfile(chan, filename, chan->language);
508 res = ast_waitstream(chan, "");
513 ast_log(LOG_WARNING, "ast_streamfile failed on %s \n", chan->name);
516 ast_stopstream(chan);
521 static int say_position(struct queue_ent *qe)
523 int res = 0, avgholdmins, avgholdsecs;
526 /* Check to see if this is ludicrous -- if we just announced position, don't do it again*/
528 if ( (now - qe->last_pos) < 15 )
531 /* If either our position has changed, or we are over the freq timer, say position */
532 if ( (qe->last_pos_said == qe->pos) && ((now - qe->last_pos) < qe->parent->announcefrequency) )
535 ast_moh_stop(qe->chan);
536 /* Say we're next, if we are */
538 res += play_file(qe->chan, qe->parent->sound_next);
541 res += play_file(qe->chan, qe->parent->sound_thereare);
542 res += ast_say_number(qe->chan, qe->pos, AST_DIGIT_ANY, qe->chan->language, (char *) NULL); /* Needs gender */
543 res += play_file(qe->chan, qe->parent->sound_calls);
545 /* Round hold time to nearest minute */
546 avgholdmins = abs(( (qe->parent->holdtime + 30) - (now - qe->start) ) / 60);
548 /* If they have specified a rounding then round the seconds as well */
549 if(qe->parent->roundingseconds) {
550 avgholdsecs = (abs(( (qe->parent->holdtime + 30) - (now - qe->start) )) - 60 * avgholdmins) / qe->parent->roundingseconds;
551 avgholdsecs*= qe->parent->roundingseconds;
556 if (option_verbose > 2)
557 ast_verbose(VERBOSE_PREFIX_3 "Hold time for %s is %d minutes %d seconds\n", qe->parent->name, avgholdmins, avgholdsecs);
559 /* If the hold time is >1 min, if it's enabled, and if it's not
560 supposed to be only once and we have already said it, say it */
561 if ((avgholdmins+avgholdsecs) > 0 && (qe->parent->announceholdtime) && (!(qe->parent->announceholdtime==1 && qe->last_pos)) ) {
562 res += play_file(qe->chan, qe->parent->sound_holdtime);
564 if (avgholdmins < 2) {
565 res += play_file(qe->chan, qe->parent->sound_lessthan);
566 res += ast_say_number(qe->chan, 2, AST_DIGIT_ANY, qe->chan->language, (char *)NULL);
568 res += ast_say_number(qe->chan, avgholdmins, AST_DIGIT_ANY, qe->chan->language, (char*) NULL);
569 res += play_file(qe->chan, qe->parent->sound_minutes);
572 res += ast_say_number(qe->chan, avgholdsecs, AST_DIGIT_ANY, qe->chan->language, (char*) NULL);
573 res += play_file(qe->chan, qe->parent->sound_seconds);
579 /* Set our last_pos indicators */
581 qe->last_pos_said = qe->pos;
583 if (option_verbose > 2)
584 ast_verbose(VERBOSE_PREFIX_3 "Told %s in %s their queue position (which was %d)\n", qe->chan->name, qe->parent->name, qe->pos);
585 res += play_file(qe->chan, qe->parent->sound_thanks);
586 ast_moh_start(qe->chan, qe->moh);
591 static void record_abandoned(struct queue_ent *qe)
593 ast_mutex_lock(&qe->parent->lock);
594 qe->parent->callsabandoned++;
595 ast_mutex_unlock(&qe->parent->lock);
598 static void recalc_holdtime(struct queue_ent *qe)
600 int oldvalue, newvalue;
602 /* Calculate holdtime using a recursive boxcar filter */
603 /* Thanks to SRT for this contribution */
604 /* 2^2 (4) is the filter coefficient; a higher exponent would give old entries more weight */
606 newvalue = time(NULL) - qe->start;
608 ast_mutex_lock(&qe->parent->lock);
609 if (newvalue <= qe->parent->servicelevel)
610 qe->parent->callscompletedinsl++;
611 oldvalue = qe->parent->holdtime;
612 qe->parent->holdtime = (((oldvalue << 2) - oldvalue) + newvalue) >> 2;
613 ast_mutex_unlock(&qe->parent->lock);
617 static void leave_queue(struct queue_ent *qe)
619 struct ast_call_queue *q;
620 struct queue_ent *cur, *prev = NULL;
625 ast_mutex_lock(&q->lock);
633 /* Take us out of the queue */
634 manager_event(EVENT_FLAG_CALL, "Leave",
635 "Channel: %s\r\nQueue: %s\r\nCount: %d\r\n",
636 qe->chan->name, q->name, q->count);
638 ast_log(LOG_NOTICE, "Queue '%s' Leave, Channel '%s'\n", q->name, qe->chan->name );
640 /* Take us out of the queue */
642 prev->next = cur->next;
646 /* Renumber the people after us in the queue based on a new count */
652 ast_mutex_unlock(&q->lock);
653 if (ast_test_flag(q, QUEUE_FLAG_DEAD) && !q->count) {
654 /* It's dead and nobody is in it, so kill it */
659 static void hanguptree(struct localuser *outgoing, struct ast_channel *exception)
661 /* Hang up a tree of stuff */
662 struct localuser *oo;
664 /* Hangup any existing lines we have open */
665 if (outgoing->chan && (outgoing->chan != exception))
666 ast_hangup(outgoing->chan);
668 outgoing=outgoing->next;
673 static int update_status(struct ast_call_queue *q, struct member *member, int status)
676 /* Since a reload could have taken place, we have to traverse the list to
677 be sure it's still valid */
678 ast_mutex_lock(&q->lock);
682 cur->status = status;
683 manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
691 q->name, cur->interface, cur->dynamic ? "dynamic" : "static",
692 cur->penalty, cur->calls, cur->lastcall, cur->status);
698 ast_mutex_unlock(&q->lock);
702 static int update_dial_status(struct ast_call_queue *q, struct member *member, int status)
704 if (status == AST_CAUSE_BUSY)
705 status = AST_DEVICE_BUSY;
706 else if (status == AST_CAUSE_UNREGISTERED)
707 status = AST_DEVICE_UNAVAILABLE;
708 else if (status == AST_CAUSE_NOSUCHDRIVER)
709 status = AST_DEVICE_INVALID;
711 status = AST_DEVICE_UNKNOWN;
712 return update_status(q, member, status);
715 static int ring_entry(struct queue_ent *qe, struct localuser *tmp)
722 if (qe->parent->wrapuptime && (time(NULL) - tmp->lastcall < qe->parent->wrapuptime)) {
724 ast_log(LOG_DEBUG, "Wrapuptime not yet expired for %s\n", tmp->interface);
726 ast_cdr_busy(qe->chan->cdr);
731 strncpy(tech, tmp->interface, sizeof(tech) - 1);
732 if ((location = strchr(tech, '/')))
737 /* Request the peer */
738 tmp->chan = ast_request(tech, qe->chan->nativeformats, location, &status);
739 if (!tmp->chan) { /* If we can't, just go on to the next call */
741 ast_log(LOG_NOTICE, "Unable to create channel of type '%s' for Queue\n", cur->tech);
744 ast_cdr_busy(qe->chan->cdr);
746 update_dial_status(qe->parent, tmp->member, status);
748 } else if (status != tmp->oldstatus)
749 update_dial_status(qe->parent, tmp->member, status);
751 tmp->chan->appl = "AppQueue";
752 tmp->chan->data = "(Outgoing Line)";
753 tmp->chan->whentohangup = 0;
754 if (tmp->chan->cid.cid_num)
755 free(tmp->chan->cid.cid_num);
756 tmp->chan->cid.cid_num = NULL;
757 if (tmp->chan->cid.cid_name)
758 free(tmp->chan->cid.cid_name);
759 tmp->chan->cid.cid_name = NULL;
760 if (tmp->chan->cid.cid_ani)
761 free(tmp->chan->cid.cid_ani);
762 tmp->chan->cid.cid_ani = NULL;
763 if (qe->chan->cid.cid_num)
764 tmp->chan->cid.cid_num = strdup(qe->chan->cid.cid_num);
765 if (qe->chan->cid.cid_name)
766 tmp->chan->cid.cid_name = strdup(qe->chan->cid.cid_name);
767 if (qe->chan->cid.cid_ani)
768 tmp->chan->cid.cid_ani = strdup(qe->chan->cid.cid_ani);
769 /* Presense of ADSI CPE on outgoing channel follows ours */
770 tmp->chan->adsicpe = qe->chan->adsicpe;
771 /* Place the call, but don't wait on the answer */
772 res = ast_call(tmp->chan, location, 0);
774 /* Again, keep going even if there's an error */
776 ast_log(LOG_DEBUG, "ast call on peer returned %d\n", res);
777 else if (option_verbose > 2)
778 ast_verbose(VERBOSE_PREFIX_3 "Couldn't call %s\n", tmp->interface);
779 ast_hangup(tmp->chan);
784 if (ast_test_flag(qe->parent, QUEUE_FLAG_EVENTWHENCALLED)) {
785 manager_event(EVENT_FLAG_AGENT, "AgentCalled",
786 "AgentCalled: %s\r\n"
787 "ChannelCalling: %s\r\n"
789 "CallerIDName: %s\r\n"
793 tmp->interface, qe->chan->name,
794 tmp->chan->cid.cid_num ? tmp->chan->cid.cid_num : "unknown",
795 tmp->chan->cid.cid_name ? tmp->chan->cid.cid_name : "unknown",
796 qe->chan->context, qe->chan->exten, qe->chan->priority);
798 if (option_verbose > 2)
799 ast_verbose(VERBOSE_PREFIX_3 "Called %s\n", tmp->interface);
804 static int ring_one(struct queue_ent *qe, struct localuser *outgoing)
806 struct localuser *cur;
807 struct localuser *best;
813 if (cur->stillgoing && /* Not already done */
814 !cur->chan && /* Isn't already going */
815 (!best || (cur->metric < bestmetric))) { /* We haven't found one yet, or it's better */
816 bestmetric = cur->metric;
822 if (!qe->parent->strategy) {
823 /* Ring everyone who shares this best metric (for ringall) */
826 if (cur->stillgoing && !cur->chan && (cur->metric == bestmetric)) {
828 ast_log(LOG_DEBUG, "(Parallel) Trying '%s' with metric %d\n", cur->interface, cur->metric);
834 /* Ring just the best channel */
836 ast_log(LOG_DEBUG, "Trying '%s' with metric %d\n", best->interface, best->metric);
837 ring_entry(qe, best);
840 } while (best && !best->chan);
843 ast_log(LOG_DEBUG, "Nobody left to try ringing in queue\n");
849 static int store_next(struct queue_ent *qe, struct localuser *outgoing)
851 struct localuser *cur;
852 struct localuser *best;
857 if (cur->stillgoing && /* Not already done */
858 !cur->chan && /* Isn't already going */
859 (!best || (cur->metric < bestmetric))) { /* We haven't found one yet, or it's better */
860 bestmetric = cur->metric;
866 /* Ring just the best channel */
868 ast_log(LOG_DEBUG, "Next is '%s' with metric %d\n", best->interface, best->metric);
869 qe->parent->rrpos = best->metric % 1000;
871 /* Just increment rrpos */
872 if (!ast_test_flag(qe->parent, QUEUE_FLAG_WRAPPED)) {
873 /* No more channels, start over */
874 qe->parent->rrpos = 0;
876 /* Prioritize next entry */
880 ast_clear_flag(qe->parent, QUEUE_FLAG_WRAPPED);
884 static int valid_exit(struct queue_ent *qe, char digit)
887 if (ast_strlen_zero(qe->context))
891 if (ast_exists_extension(qe->chan, qe->context, tmp, 1, qe->chan->cid.cid_num)) {
892 strncpy(qe->chan->context, qe->context, sizeof(qe->chan->context) - 1);
893 strncpy(qe->chan->exten, tmp, sizeof(qe->chan->exten) - 1);
894 qe->chan->priority = 0;
900 #define AST_MAX_WATCHERS 256
902 static struct localuser *wait_for_answer(struct queue_ent *qe, struct localuser *outgoing, int *to, struct ast_flags *flags, char *digit)
904 char *queue = qe->parent->name;
914 struct localuser *peer = NULL;
915 struct ast_channel *watchers[AST_MAX_WATCHERS];
917 struct ast_channel *winner;
918 struct ast_channel *in = qe->chan;
920 while(*to && !peer) {
927 /* Keep track of important channels */
928 if (o->stillgoing && o->chan) {
929 watchers[pos++] = o->chan;
936 if (numlines == (numbusies + numnochan)) {
937 ast_log(LOG_DEBUG, "Everyone is busy at this time\n");
939 ast_log(LOG_NOTICE, "No one is answering queue '%s'\n", queue);
944 winner = ast_waitfor_n(watchers, pos, to);
947 if (o->stillgoing && (o->chan) && (o->chan->_state == AST_STATE_UP)) {
949 if (option_verbose > 2)
950 ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
952 ast_copy_flags(flags, o, QUEUE_FLAG_REDIR_IN & QUEUE_FLAG_REDIR_OUT & QUEUE_FLAG_DISCON_IN & QUEUE_FLAG_DISCON_OUT);
954 } else if (o->chan && (o->chan == winner)) {
955 if (!ast_strlen_zero(o->chan->call_forward)) {
956 char tmpchan[256]="";
959 strncpy(tmpchan, o->chan->call_forward, sizeof(tmpchan) - 1);
960 if ((stuff = strchr(tmpchan, '/'))) {
965 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", o->chan->call_forward, o->chan->context);
969 /* Before processing channel, go ahead and check for forwarding */
970 if (option_verbose > 2)
971 ast_verbose(VERBOSE_PREFIX_3 "Now forwarding %s to '%s/%s' (thanks to %s)\n", in->name, tech, stuff, o->chan->name);
972 /* Setup parameters */
973 o->chan = ast_request(tech, in->nativeformats, stuff, &status);
974 if (status != o->oldstatus)
975 update_dial_status(qe->parent, o->member, status);
977 ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s'\n", tech, stuff);
981 if (o->chan->cid.cid_num)
982 free(o->chan->cid.cid_num);
983 o->chan->cid.cid_num = NULL;
984 if (o->chan->cid.cid_name)
985 free(o->chan->cid.cid_name);
986 o->chan->cid.cid_name = NULL;
988 if (in->cid.cid_num) {
989 o->chan->cid.cid_num = strdup(in->cid.cid_num);
990 if (!o->chan->cid.cid_num)
991 ast_log(LOG_WARNING, "Out of memory\n");
993 if (in->cid.cid_name) {
994 o->chan->cid.cid_name = strdup(in->cid.cid_name);
995 if (!o->chan->cid.cid_name)
996 ast_log(LOG_WARNING, "Out of memory\n");
998 strncpy(o->chan->accountcode, in->accountcode, sizeof(o->chan->accountcode) - 1);
999 o->chan->cdrflags = in->cdrflags;
1001 if (in->cid.cid_ani) {
1002 if (o->chan->cid.cid_ani)
1003 free(o->chan->cid.cid_ani);
1004 o->chan->cid.cid_ani = malloc(strlen(in->cid.cid_ani) + 1);
1005 if (o->chan->cid.cid_ani)
1006 strncpy(o->chan->cid.cid_ani, in->cid.cid_ani, strlen(in->cid.cid_ani) + 1);
1008 ast_log(LOG_WARNING, "Out of memory\n");
1010 if (o->chan->cid.cid_rdnis)
1011 free(o->chan->cid.cid_rdnis);
1012 if (!ast_strlen_zero(in->macroexten))
1013 o->chan->cid.cid_rdnis = strdup(in->macroexten);
1015 o->chan->cid.cid_rdnis = strdup(in->exten);
1016 if (ast_call(o->chan, tmpchan, 0)) {
1017 ast_log(LOG_NOTICE, "Failed to dial on local channel for call forward to '%s'\n", tmpchan);
1019 ast_hangup(o->chan);
1024 /* Hangup the original channel now, in case we needed it */
1028 f = ast_read(winner);
1030 if (f->frametype == AST_FRAME_CONTROL) {
1031 switch(f->subclass) {
1032 case AST_CONTROL_ANSWER:
1033 /* This is our guy if someone answered. */
1035 if (option_verbose > 2)
1036 ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
1038 ast_copy_flags(flags, o, QUEUE_FLAG_REDIR_IN & QUEUE_FLAG_REDIR_OUT & QUEUE_FLAG_DISCON_IN & QUEUE_FLAG_DISCON_OUT);
1041 case AST_CONTROL_BUSY:
1042 if (option_verbose > 2)
1043 ast_verbose( VERBOSE_PREFIX_3 "%s is busy\n", o->chan->name);
1046 ast_cdr_busy(in->cdr);
1047 ast_hangup(o->chan);
1049 if (qe->parent->strategy)
1050 ring_one(qe, outgoing);
1053 case AST_CONTROL_CONGESTION:
1054 if (option_verbose > 2)
1055 ast_verbose( VERBOSE_PREFIX_3 "%s is circuit-busy\n", o->chan->name);
1058 ast_cdr_busy(in->cdr);
1059 ast_hangup(o->chan);
1061 if (qe->parent->strategy)
1062 ring_one(qe, outgoing);
1065 case AST_CONTROL_RINGING:
1066 if (option_verbose > 2)
1067 ast_verbose( VERBOSE_PREFIX_3 "%s is ringing\n", o->chan->name);
1070 ast_indicate(in, AST_CONTROL_RINGING);
1075 case AST_CONTROL_OFFHOOK:
1076 /* Ignore going off hook */
1079 ast_log(LOG_DEBUG, "Dunno what to do with control type %d\n", f->subclass);
1085 ast_hangup(o->chan);
1087 if (qe->parent->strategy)
1088 ring_one(qe, outgoing);
1096 if (f && (f->frametype != AST_FRAME_VOICE))
1097 printf("Frame type: %d, %d\n", f->frametype, f->subclass);
1098 else if (!f || (f->frametype != AST_FRAME_VOICE))
1099 printf("Hangup received on %s\n", in->name);
1101 if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))) {
1106 if (f && (f->frametype == AST_FRAME_DTMF) && ast_test_flag(flags, QUEUE_FLAG_DISCON_OUT) && (f->subclass == '*')) {
1107 if (option_verbose > 3)
1108 ast_verbose(VERBOSE_PREFIX_3 "User hit %c to disconnect call.\n", f->subclass);
1112 if (f && (f->frametype == AST_FRAME_DTMF) && (f->subclass != '*') && valid_exit(qe, f->subclass)) {
1113 if (option_verbose > 3)
1114 ast_verbose(VERBOSE_PREFIX_3 "User pressed digit: %c", f->subclass);
1120 if (!*to && (option_verbose > 2))
1121 ast_verbose( VERBOSE_PREFIX_3 "Nobody picked up in %d ms\n", orig);
1128 static int is_our_turn(struct queue_ent *qe)
1130 struct queue_ent *ch;
1133 /* Atomically read the parent head -- does not need a lock */
1134 ch = qe->parent->head;
1135 /* If we are now at the top of the head, break out */
1138 ast_log(LOG_DEBUG, "It's our turn (%s).\n", qe->chan->name);
1142 ast_log(LOG_DEBUG, "It's not our turn (%s).\n", qe->chan->name);
1148 static int wait_our_turn(struct queue_ent *qe, int ringing)
1152 /* This is the holding pen for callers 2 through maxlen */
1154 if (is_our_turn(qe))
1157 /* If we have timed out, break out */
1158 if (qe->expire && (time(NULL) > qe->expire))
1161 /* leave the queue if no agents, if enabled */
1162 if (ast_test_flag(qe->parent, QUEUE_FLAG_LEAVEWHENEMPTY) && has_no_members(qe->parent)) {
1167 /* Make a position announcement, if enabled */
1168 if (qe->parent->announcefrequency && !ringing)
1171 /* Wait a second before checking again */
1172 res = ast_waitfordigit(qe->chan, RECHECK * 1000);
1179 static int update_queue(struct ast_call_queue *q, struct member *member)
1182 /* Since a reload could have taken place, we have to traverse the list to
1183 be sure it's still valid */
1184 ast_mutex_lock(&q->lock);
1187 if (member == cur) {
1188 time(&cur->lastcall);
1194 q->callscompleted++;
1195 ast_mutex_unlock(&q->lock);
1199 static int calc_metric(struct ast_call_queue *q, struct member *mem, int pos, struct queue_ent *qe, struct localuser *tmp)
1201 switch (q->strategy) {
1202 case QUEUE_STRATEGY_RINGALL:
1203 /* Everyone equal, except for penalty */
1204 tmp->metric = mem->penalty * 1000000;
1206 case QUEUE_STRATEGY_ROUNDROBIN:
1208 if (!ast_test_flag(q, QUEUE_FLAG_WRAPPED)) {
1209 /* No more channels, start over */
1212 /* Prioritize next entry */
1215 ast_clear_flag(q, QUEUE_FLAG_WRAPPED);
1218 case QUEUE_STRATEGY_RRMEMORY:
1219 if (pos < q->rrpos) {
1220 tmp->metric = 1000 + pos;
1222 if (pos > q->rrpos) {
1223 /* Indicate there is another priority */
1224 ast_set_flag(q, QUEUE_FLAG_WRAPPED);
1228 tmp->metric += mem->penalty * 1000000;
1230 case QUEUE_STRATEGY_RANDOM:
1231 tmp->metric = rand() % 1000;
1232 tmp->metric += mem->penalty * 1000000;
1234 case QUEUE_STRATEGY_FEWESTCALLS:
1235 tmp->metric = mem->calls;
1236 tmp->metric += mem->penalty * 1000000;
1238 case QUEUE_STRATEGY_LEASTRECENT:
1242 tmp->metric = 1000000 - (time(NULL) - mem->lastcall);
1243 tmp->metric += mem->penalty * 1000000;
1246 ast_log(LOG_WARNING, "Can't calculate metric for unknown strategy %d\n", q->strategy);
1252 static int try_calling(struct queue_ent *qe, char *options, char *announceoverride, char *url, int *go_on)
1255 struct localuser *outgoing=NULL, *tmp = NULL;
1257 struct ast_flags flags;
1258 char restofit[AST_MAX_EXTENSION];
1259 char oldexten[AST_MAX_EXTENSION]="";
1260 char oldcontext[AST_MAX_EXTENSION]="";
1261 char queuename[256]="";
1263 char *monitorfilename;
1264 struct ast_channel *peer;
1265 struct localuser *lpeer;
1266 struct member *member;
1267 int res = 0, bridge = 0;
1270 char *announce = NULL;
1274 struct ast_bridge_config config;
1275 /* Hold the lock while we setup the outgoing calls */
1276 ast_mutex_lock(&qe->parent->lock);
1278 ast_log(LOG_DEBUG, "%s is trying to call a queue member.\n",
1280 strncpy(queuename, qe->parent->name, sizeof(queuename) - 1);
1282 cur = qe->parent->members;
1283 if (!ast_strlen_zero(qe->announce))
1284 announce = qe->announce;
1285 if (announceoverride && !ast_strlen_zero(announceoverride))
1286 announce = announceoverride;
1288 /* Get a technology/[device:]number pair */
1289 tmp = malloc(sizeof(struct localuser));
1291 ast_mutex_unlock(&qe->parent->lock);
1292 ast_log(LOG_WARNING, "Out of memory\n");
1295 memset(tmp, 0, sizeof(struct localuser));
1296 tmp->stillgoing = -1;
1297 for (; options && *options; options++)
1300 ast_set_flag(tmp, QUEUE_FLAG_REDIR_IN);
1303 ast_set_flag(tmp, QUEUE_FLAG_REDIR_OUT);
1306 ast_set_flag(tmp, QUEUE_FLAG_RINGBACKONLY);
1309 ast_set_flag(tmp, QUEUE_FLAG_MUSICONHOLD);
1312 ast_set_flag(tmp, QUEUE_FLAG_DATAQUALITY);
1315 ast_set_flag(tmp, QUEUE_FLAG_DISCON_IN);
1318 ast_set_flag(tmp, QUEUE_FLAG_DISCON_OUT);
1321 if ((now - qe->start >= qe->parent->timeout))
1327 ast_log(LOG_DEBUG, "Queue with URL=%s_\n", url);
1329 ast_log(LOG_DEBUG, "Simple queue (no URL)\n");
1332 tmp->member = cur; /* Never directly dereference! Could change on reload */
1333 tmp->oldstatus = cur->status;
1334 tmp->lastcall = cur->lastcall;
1335 strncpy(tmp->interface, cur->interface, sizeof(tmp->interface)-1);
1336 /* If we're dialing by extension, look at the extension to know what to dial */
1337 if ((newnum = strstr(tmp->interface, "/BYEXTENSION"))) {
1339 strncpy(restofit, newnum + strlen("BYEXTENSION"), sizeof(restofit) - 1);
1340 snprintf(newnum, sizeof(tmp->interface) - (newnum - tmp->interface), "%s%s", qe->chan->exten, restofit);
1342 ast_log(LOG_DEBUG, "Dialing by extension %s\n", tmp->interface);
1344 /* Special case: If we ring everyone, go ahead and ring them, otherwise
1345 just calculate their metric for the appropriate strategy */
1346 calc_metric(qe->parent, cur, x++, qe, tmp);
1347 /* Put them in the list of outgoing thingies... We're ready now.
1348 XXX If we're forcibly removed, these outgoing calls won't get
1350 tmp->next = outgoing;
1352 /* If this line is up, don't try anybody else */
1353 if (outgoing->chan && (outgoing->chan->_state == AST_STATE_UP))
1358 if (qe->parent->timeout)
1359 to = qe->parent->timeout * 1000;
1362 ring_one(qe, outgoing);
1363 ast_mutex_unlock(&qe->parent->lock);
1364 lpeer = wait_for_answer(qe, outgoing, &to, &flags, &digit);
1365 ast_mutex_lock(&qe->parent->lock);
1366 if (qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY) {
1367 store_next(qe, outgoing);
1369 ast_mutex_unlock(&qe->parent->lock);
1376 /* Musta gotten hung up */
1377 record_abandoned(qe);
1380 if (digit && valid_exit(qe, digit))
1383 /* Nobody answered, next please? */
1387 ast_log(LOG_DEBUG, "%s: Nobody answered.\n", qe->chan->name);
1391 /* Ah ha! Someone answered within the desired timeframe. Of course after this
1392 we will always return with -1 so that it is hung up properly after the
1395 if (!strcmp(qe->chan->type,"Zap")) {
1396 zapx = !ast_test_flag(tmp, QUEUE_FLAG_DATAQUALITY);
1397 ast_channel_setoption(qe->chan,AST_OPTION_TONE_VERIFY,&zapx,sizeof(char),0);
1399 if (!strcmp(peer->type,"Zap")) {
1400 zapx = !ast_test_flag(tmp, QUEUE_FLAG_DATAQUALITY);
1401 ast_channel_setoption(peer,AST_OPTION_TONE_VERIFY,&zapx,sizeof(char),0);
1403 /* Update parameters for the queue */
1404 recalc_holdtime(qe);
1405 member = lpeer->member;
1406 hanguptree(outgoing, peer);
1408 if (announce || ast_test_flag(qe->parent, QUEUE_FLAG_REPORTHOLDTIME) || qe->parent->memberdelay) {
1410 res2 = ast_autoservice_start(qe->chan);
1412 if (qe->parent->memberdelay) {
1413 ast_log(LOG_NOTICE, "Delaying member connect for %d seconds\n", qe->parent->memberdelay);
1414 res2 |= ast_safe_sleep(peer, qe->parent->memberdelay * 1000);
1416 if (!res2 && announce) {
1417 if (play_file(peer, announce))
1418 ast_log(LOG_WARNING, "Announcement file '%s' is unavailable, continuing anyway...\n", announce);
1420 if (!res2 && ast_test_flag(qe->parent, QUEUE_FLAG_REPORTHOLDTIME)) {
1421 if (!play_file(peer, qe->parent->sound_reporthold)) {
1426 holdtime = abs((now - qe->start) / 60);
1428 play_file(peer, qe->parent->sound_lessthan);
1429 ast_say_number(peer, 2, AST_DIGIT_ANY, peer->language, NULL);
1431 ast_say_number(peer, holdtime, AST_DIGIT_ANY, peer->language, NULL);
1432 play_file(peer, qe->parent->sound_minutes);
1436 res2 |= ast_autoservice_stop(qe->chan);
1438 /* Agent must have hung up */
1439 ast_log(LOG_WARNING, "Agent on %s hungup on the customer. They're going to be pissed.\n", peer->name);
1440 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "AGENTDUMP", "%s", "");
1445 /* Stop music on hold */
1446 ast_moh_stop(qe->chan);
1447 /* If appropriate, log that we have a destination channel */
1449 ast_cdr_setdestchan(qe->chan->cdr, peer->name);
1450 /* Make sure channels are compatible */
1451 res = ast_channel_make_compatible(qe->chan, peer);
1453 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "SYSCOMPAT", "%s", "");
1454 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", qe->chan->name, peer->name);
1458 /* Begin Monitoring */
1459 if (qe->parent->monfmt && *qe->parent->monfmt) {
1460 monitorfilename = pbx_builtin_getvar_helper( qe->chan, "MONITOR_FILENAME");
1461 if(monitorfilename) {
1462 ast_monitor_start( peer, qe->parent->monfmt, monitorfilename, 1 );
1464 ast_monitor_start( peer, qe->parent->monfmt, qe->chan->cdr->uniqueid, 1 );
1466 if(ast_test_flag(qe->parent, QUEUE_FLAG_MONJOIN)) {
1467 ast_monitor_setjoinfiles( peer, 1);
1470 /* Drop out of the queue at this point, to prepare for next caller */
1472 if( url && !ast_strlen_zero(url) && ast_channel_supports_html(peer) ) {
1474 ast_log(LOG_DEBUG, "app_queue: sendurl=%s.\n", url);
1475 ast_channel_sendurl( peer, url );
1477 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "CONNECT", "%ld", (long)time(NULL) - qe->start);
1478 strncpy(oldcontext, qe->chan->context, sizeof(oldcontext) - 1);
1479 strncpy(oldexten, qe->chan->exten, sizeof(oldexten) - 1);
1482 memset(&config,0,sizeof(struct ast_bridge_config));
1483 if (ast_test_flag(&flags, QUEUE_FLAG_REDIR_IN))
1484 config.features_callee |= AST_FEATURE_REDIRECT;
1485 if (ast_test_flag(&flags, QUEUE_FLAG_REDIR_OUT))
1486 config.features_caller |= AST_FEATURE_REDIRECT;
1487 if (ast_test_flag(&flags, QUEUE_FLAG_DISCON_IN))
1488 config.features_callee |= AST_FEATURE_DISCONNECT;
1489 if (ast_test_flag(&flags, QUEUE_FLAG_DISCON_OUT))
1490 config.features_caller |= AST_FEATURE_DISCONNECT;
1491 bridge = ast_bridge_call(qe->chan,peer,&config);
1493 if (strcasecmp(oldcontext, qe->chan->context) || strcasecmp(oldexten, qe->chan->exten)) {
1494 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "TRANSFER", "%s|%s", qe->chan->exten, qe->chan->context);
1495 } else if (qe->chan->_softhangup) {
1496 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "COMPLETECALLER", "%ld|%ld", (long)(callstart - qe->start), (long)(time(NULL) - callstart));
1498 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "COMPLETEAGENT", "%ld|%ld", (long)(callstart - qe->start), (long)(time(NULL) - callstart));
1501 if(bridge != AST_PBX_NO_HANGUP_PEER)
1503 update_queue(qe->parent, member);
1505 res = 1; /* JDG: bridge successfull, leave app_queue */
1507 res = bridge; /* bridge error, stay in the queue */
1510 hanguptree(outgoing, NULL);
1514 static int wait_a_bit(struct queue_ent *qe)
1516 /* Don't need to hold the lock while we setup the outgoing calls */
1517 int retrywait = qe->parent->retry * 1000;
1518 return ast_waitfordigit(qe->chan, retrywait);
1521 /* [PHM 06/26/03] */
1523 static struct member * interface_exists(struct ast_call_queue *q, char *interface)
1528 for (mem = q->members; mem; mem = mem->next)
1529 if (!strcmp(interface, mem->interface))
1536 static struct member *create_queue_node(char *interface, int penalty)
1540 /* Add a new member */
1542 cur = malloc(sizeof(struct member));
1545 memset(cur, 0, sizeof(struct member));
1546 cur->penalty = penalty;
1547 strncpy(cur->interface, interface, sizeof(cur->interface) - 1);
1548 if (!strchr(cur->interface, '/'))
1549 ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
1550 cur->status = ast_device_state(interface);
1556 /* Dump all members in a specific queue to the databse
1558 * <pm_family>/<queuename> = <interface>;<penalty>;...
1561 static void dump_queue_members(struct ast_call_queue *pm_queue)
1563 struct member *cur_member = NULL;
1564 char value[PM_MAX_LEN];
1568 memset(value, 0, sizeof(value));
1571 cur_member = pm_queue->members;
1572 while (cur_member) {
1573 if (cur_member->dynamic) {
1574 value_len = strlen(value);
1575 res = snprintf(value+value_len, sizeof(value)-value_len, "%s;%d;", cur_member->interface, cur_member->penalty);
1576 if (res != strlen(value + value_len)) {
1577 ast_log(LOG_WARNING, "Could not create persistent member string, out of space\n");
1581 cur_member = cur_member->next;
1584 if (!ast_strlen_zero(value) && !cur_member) {
1585 if (ast_db_put(pm_family, pm_queue->name, value))
1586 ast_log(LOG_WARNING, "failed to create persistent dynamic entry!\n");
1588 /* Delete the entry if the queue is empty or there is an error */
1589 ast_db_del(pm_family, pm_queue->name);
1596 static int remove_from_queue(char *queuename, char *interface)
1598 struct ast_call_queue *q;
1599 struct member *last_member, *look;
1600 int res = RES_NOSUCHQUEUE;
1602 ast_mutex_lock(&qlock);
1603 for (q = queues ; q ; q = q->next) {
1604 ast_mutex_lock(&q->lock);
1605 if (!strcmp(q->name, queuename)) {
1606 if ((last_member = interface_exists(q, interface))) {
1607 if ((look = q->members) == last_member) {
1608 q->members = last_member->next;
1610 while (look != NULL) {
1611 if (look->next == last_member) {
1612 look->next = last_member->next;
1619 manager_event(EVENT_FLAG_AGENT, "QueueMemberRemoved",
1622 q->name, last_member->interface);
1625 if (queue_persistent_members)
1626 dump_queue_members(q);
1632 ast_mutex_unlock(&q->lock);
1635 ast_mutex_unlock(&q->lock);
1637 ast_mutex_unlock(&qlock);
1641 static int add_to_queue(char *queuename, char *interface, int penalty)
1643 struct ast_call_queue *q;
1644 struct member *new_member;
1645 int res = RES_NOSUCHQUEUE;
1647 ast_mutex_lock(&qlock);
1648 for (q = queues ; q ; q = q->next) {
1649 ast_mutex_lock(&q->lock);
1650 if (!strcmp(q->name, queuename)) {
1651 if (interface_exists(q, interface) == NULL) {
1652 new_member = create_queue_node(interface, penalty);
1654 if (new_member != NULL) {
1655 new_member->dynamic = 1;
1656 new_member->next = q->members;
1657 q->members = new_member;
1658 manager_event(EVENT_FLAG_AGENT, "QueueMemberAdded",
1661 "Membership: %s\r\n"
1663 "CallsTaken: %d\r\n"
1666 q->name, new_member->interface, new_member->dynamic ? "dynamic" : "static",
1667 new_member->penalty, new_member->calls, new_member->lastcall, new_member->status);
1669 if (queue_persistent_members)
1670 dump_queue_members(q);
1674 res = RES_OUTOFMEMORY;
1679 ast_mutex_unlock(&q->lock);
1682 ast_mutex_unlock(&q->lock);
1684 ast_mutex_unlock(&qlock);
1688 /* Add members saved in the queue members DB file saves
1689 * created by dump_queue_members(), back into the queues */
1690 static void reload_queue_members(void)
1693 char *pm_queue_name;
1695 char *pm_penalty_tok;
1697 struct ast_db_entry *pm_db_tree = NULL;
1698 int pm_family_len = 0;
1699 struct ast_call_queue *cur_queue = NULL;
1700 char queue_data[PM_MAX_LEN];
1702 pm_db_tree = ast_db_gettree(pm_family, NULL);
1704 pm_family_len = strlen(pm_family);
1705 ast_mutex_lock(&qlock);
1706 /* Each key in 'pm_family' is the name of a specific queue in which
1707 * we will reload members into. */
1708 while (pm_db_tree) {
1709 pm_queue_name = pm_db_tree->key+pm_family_len+2;
1713 ast_mutex_lock(&cur_queue->lock);
1715 if (strcmp(pm_queue_name, cur_queue->name) == 0)
1718 ast_mutex_unlock(&cur_queue->lock);
1720 cur_queue = cur_queue->next;
1724 /* If the queue no longer exists, remove it from the
1726 ast_db_del(pm_family, pm_queue_name);
1727 pm_db_tree = pm_db_tree->next;
1730 ast_mutex_unlock(&cur_queue->lock);
1732 if (!ast_db_get(pm_family, pm_queue_name, queue_data, PM_MAX_LEN)) {
1733 /* Parse each <interface>;<penalty>; from the value of the
1734 * queuename key and add it to the respective queue */
1735 cur_pm_ptr = queue_data;
1736 while ((pm_interface = strsep(&cur_pm_ptr, ";"))) {
1737 if (!(pm_penalty_tok = strsep(&cur_pm_ptr, ";"))) {
1738 ast_log(LOG_WARNING, "Error parsing corrupted Queue DB string for '%s'\n", pm_queue_name);
1741 pm_penalty = strtol(pm_penalty_tok, NULL, 10);
1742 if (errno == ERANGE) {
1743 ast_log(LOG_WARNING, "Error converting penalty: %s: Out of range.\n", pm_penalty_tok);
1748 ast_log(LOG_DEBUG, "Reload Members: Queue: %s Member: %s Penalty: %d\n", pm_queue_name, pm_interface, pm_penalty);
1750 if (add_to_queue(pm_queue_name, pm_interface, pm_penalty) == RES_OUTOFMEMORY) {
1751 ast_log(LOG_ERROR, "Out of Memory when loading queue member from astdb\n");
1757 pm_db_tree = pm_db_tree->next;
1760 ast_log(LOG_NOTICE, "Queue members sucessfully reloaded from database.\n");
1761 ast_mutex_unlock(&qlock);
1763 ast_db_freetree(pm_db_tree);
1768 static int rqm_exec(struct ast_channel *chan, void *data)
1771 struct localuser *u;
1772 char *info, *queuename;
1773 char tmpchan[256]="";
1774 char *interface = NULL;
1777 ast_log(LOG_WARNING, "RemoveQueueMember requires an argument (queuename[|interface])\n");
1781 info = ast_strdupa((char *)data);
1783 ast_log(LOG_ERROR, "Out of memory\n");
1791 interface = strchr(queuename, '|');
1797 strncpy(tmpchan, chan->name, sizeof(tmpchan) - 1);
1798 interface = strrchr(tmpchan, '-');
1801 interface = tmpchan;
1805 switch (remove_from_queue(queuename, interface)) {
1807 ast_log(LOG_NOTICE, "Removed interface '%s' from queue '%s'\n", interface, queuename);
1811 ast_log(LOG_WARNING, "Unable to remove interface '%s' from queue '%s': Not there\n", interface, queuename);
1812 if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 101, chan->cid.cid_num)) {
1813 chan->priority += 100;
1817 case RES_NOSUCHQUEUE:
1818 ast_log(LOG_WARNING, "Unable to remove interface from queue '%s': No such queue\n", queuename);
1821 case RES_OUTOFMEMORY:
1822 ast_log(LOG_ERROR, "Out of memory\n");
1826 LOCAL_USER_REMOVE(u);
1830 static int aqm_exec(struct ast_channel *chan, void *data)
1833 struct localuser *u;
1836 char tmpchan[512]="";
1837 char *interface=NULL;
1838 char *penaltys=NULL;
1842 ast_log(LOG_WARNING, "AddQueueMember requires an argument (queuename[|[interface][|penalty]])\n");
1846 info = ast_strdupa((char *)data);
1848 ast_log(LOG_ERROR, "Out of memory\n");
1855 interface = strchr(queuename, '|');
1861 penaltys = strchr(interface, '|');
1867 if (!interface || ast_strlen_zero(interface)) {
1868 strncpy(tmpchan, chan->name, sizeof(tmpchan) - 1);
1869 interface = strrchr(tmpchan, '-');
1872 interface = tmpchan;
1874 if (penaltys && !ast_strlen_zero(penaltys)) {
1875 if ((sscanf(penaltys, "%d", &penalty) != 1) || penalty < 0) {
1876 ast_log(LOG_WARNING, "Penalty '%s' is invalid, must be an integer >= 0\n", penaltys);
1882 switch (add_to_queue(queuename, interface, penalty)) {
1884 ast_log(LOG_NOTICE, "Added interface '%s' to queue '%s'\n", interface, queuename);
1888 ast_log(LOG_WARNING, "Unable to add interface '%s' to queue '%s': Already there\n", interface, queuename);
1889 if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 101, chan->cid.cid_num)) {
1890 chan->priority += 100;
1894 case RES_NOSUCHQUEUE:
1895 ast_log(LOG_WARNING, "Unable to add interface to queue '%s': No such queue\n", queuename);
1898 case RES_OUTOFMEMORY:
1899 ast_log(LOG_ERROR, "Out of memory adding member %s to queue %s\n", interface, queuename);
1903 LOCAL_USER_REMOVE(u);
1907 static int queue_exec(struct ast_channel *chan, void *data)
1911 struct localuser *u;
1914 char *info_ptr = info;
1915 char *options = NULL;
1917 char *announceoverride = NULL;
1918 char *user_priority;
1920 char *queuetimeoutstr = NULL;
1922 /* whether to exit Queue application after the timeout hits */
1925 /* Our queue entry */
1926 struct queue_ent qe;
1928 if (!data || ast_strlen_zero(data)) {
1929 ast_log(LOG_WARNING, "Queue requires an argument: queuename[|options[|URL][|announceoverride][|timeout]]\n");
1935 /* Setup our queue entry */
1936 memset(&qe, 0, sizeof(qe));
1937 qe.start = time(NULL);
1939 /* Parse our arguments XXX Check for failure XXX */
1940 strncpy(info, (char *) data, sizeof(info) - 1);
1941 queuename = strsep(&info_ptr, "|");
1942 options = strsep(&info_ptr, "|");
1943 url = strsep(&info_ptr, "|");
1944 announceoverride = strsep(&info_ptr, "|");
1945 queuetimeoutstr = info_ptr;
1947 /* set the expire time based on the supplied timeout; */
1948 if (queuetimeoutstr)
1949 qe.expire = qe.start + atoi(queuetimeoutstr);
1953 /* Get the priority from the variable ${QUEUE_PRIO} */
1954 user_priority = pbx_builtin_getvar_helper(chan, "QUEUE_PRIO");
1955 if (user_priority) {
1956 if (sscanf(user_priority, "%d", &prio) == 1) {
1958 ast_log(LOG_DEBUG, "%s: Got priority %d from ${QUEUE_PRIO}.\n",
1961 ast_log(LOG_WARNING, "${QUEUE_PRIO}: Invalid value (%s), channel %s.\n",
1962 user_priority, chan->name);
1966 if (option_debug > 2)
1967 ast_log(LOG_DEBUG, "NO QUEUE_PRIO variable found. Using default.\n");
1972 if (strchr(options, 'r')) {
1978 ast_log(LOG_DEBUG, "queue: %s, options: %s, url: %s, announce: %s, expires: %ld, priority: %d\n",
1979 queuename, options, url, announceoverride, (long)qe.expire, (int)prio);
1982 qe.prio = (int)prio;
1983 qe.last_pos_said = 0;
1985 if (!join_queue(queuename, &qe)) {
1986 ast_queue_log(queuename, chan->uniqueid, "NONE", "ENTERQUEUE", "%s|%s", url ? url : "", chan->cid.cid_num ? chan->cid.cid_num : "");
1987 /* Start music on hold */
1990 ast_indicate(chan, AST_CONTROL_RINGING);
1992 ast_moh_start(chan, qe.moh);
1995 /* This is the wait loop for callers 2 through maxlen */
1997 res = wait_our_turn(&qe, ringing);
1998 /* If they hungup, return immediately */
2000 /* Record this abandoned call */
2001 record_abandoned(&qe);
2002 ast_queue_log(queuename, chan->uniqueid, "NONE", "ABANDON", "%d|%d|%ld", qe.pos, qe.opos, (long)time(NULL) - qe.start);
2003 if (option_verbose > 2) {
2004 ast_verbose(VERBOSE_PREFIX_3 "User disconnected from queue %s while waiting their turn\n", queuename);
2011 if (valid_exit(&qe, res)) {
2012 ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHKEY", "%c|%d", res, qe.pos);
2017 int makeannouncement = 0;
2019 /* This is the wait loop for the head caller*/
2020 /* To exit, they may get their call answered; */
2021 /* they may dial a digit from the queue context; */
2022 /* or, they may timeout. */
2024 /* Leave if we have exceeded our queuetimeout */
2025 if (qe.expire && (time(NULL) > qe.expire)) {
2030 if (makeannouncement) {
2031 /* Make a position announcement, if enabled */
2032 if (qe.parent->announcefrequency && !ringing)
2035 makeannouncement = 1;
2037 /* Try calling all queue members for 'timeout' seconds */
2038 res = try_calling(&qe, options, announceoverride, url, &go_on);
2042 ast_queue_log(queuename, chan->uniqueid, "NONE", "ABANDON", "%d|%d|%ld", qe.pos, qe.opos, (long)time(NULL) - qe.start);
2044 ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHKEY", "%c|%d", res, qe.pos);
2048 /* leave the queue if no agents, if enabled */
2049 if (ast_test_flag(qe.parent, QUEUE_FLAG_LEAVEWHENEMPTY) && has_no_members(qe.parent)) {
2054 /* Leave if we have exceeded our queuetimeout */
2055 if (qe.expire && (time(NULL) > qe.expire)) {
2060 /* OK, we didn't get anybody; wait for 'retry' seconds; may get a digit to exit with */
2061 res = wait_a_bit(&qe);
2063 ast_queue_log(queuename, chan->uniqueid, "NONE", "ABANDON", "%d|%d|%ld", qe.pos, qe.opos, (long)time(NULL) - qe.start);
2064 if (option_verbose > 2) {
2065 ast_verbose(VERBOSE_PREFIX_3 "User disconnected from queue %s when they almost made it\n", queuename);
2070 if (res && valid_exit(&qe, res)) {
2071 ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHKEY", "%c|%d", res, qe.pos);
2074 /* exit after 'timeout' cycle if 'n' option enabled */
2076 if (option_verbose > 2) {
2077 ast_verbose(VERBOSE_PREFIX_3 "Exiting on time-out cycle\n");
2080 ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHTIMEOUT", "%d", qe.pos);
2084 /* Since this is a priority queue and
2085 * it is not sure that we are still at the head
2086 * of the queue, go and check for our turn again.
2088 if (!is_our_turn(&qe)) {
2090 ast_log(LOG_DEBUG, "Darn priorities, going back in queue (%s)!\n",
2096 /* Don't allow return code > 0 */
2097 if (res >= 0 && res != AST_PBX_KEEPALIVE) {
2100 ast_indicate(chan, -1);
2104 ast_stopstream(chan);
2108 ast_log(LOG_WARNING, "Unable to join queue '%s'\n", queuename);
2111 LOCAL_USER_REMOVE(u);
2115 static void reload_queues(void)
2117 struct ast_call_queue *q, *ql, *qn;
2118 struct ast_config *cfg;
2120 struct ast_variable *var;
2121 struct member *prev, *cur;
2123 char *general_val = NULL;
2125 cfg = ast_load("queues.conf");
2127 ast_log(LOG_NOTICE, "No call queueing config file (queues.conf), so no call queues\n");
2130 ast_mutex_lock(&qlock);
2131 /* Mark all queues as dead for the moment */
2134 ast_set_flag(q, QUEUE_FLAG_DEAD);
2137 /* Chug through config file */
2138 cat = ast_category_browse(cfg, NULL);
2140 if (strcasecmp(cat, "general")) { /* Define queue */
2141 /* Look for an existing one */
2144 if (!strcmp(q->name, cat))
2150 q = malloc(sizeof(struct ast_call_queue));
2153 memset(q, 0, sizeof(struct ast_call_queue));
2154 ast_mutex_init(&q->lock);
2155 strncpy(q->name, cat, sizeof(q->name) - 1);
2162 ast_mutex_lock(&q->lock);
2163 /* Re-initialize the queue */
2164 ast_clear_flag(q, QUEUE_FLAG_DEAD);
2168 q->announcefrequency = 0;
2169 q->announceholdtime = 0;
2170 q->roundingseconds = 0; /* Default - don't announce seconds */
2172 q->callscompleted = 0;
2173 q->callsabandoned = 0;
2174 q->callscompletedinsl = 0;
2175 q->servicelevel = 0;
2179 q->announce[0] = '\0';
2180 q->context[0] = '\0';
2181 q->monfmt[0] = '\0';
2182 strncpy(q->sound_next, "queue-youarenext", sizeof(q->sound_next) - 1);
2183 strncpy(q->sound_thereare, "queue-thereare", sizeof(q->sound_thereare) - 1);
2184 strncpy(q->sound_calls, "queue-callswaiting", sizeof(q->sound_calls) - 1);
2185 strncpy(q->sound_holdtime, "queue-holdtime", sizeof(q->sound_holdtime) - 1);
2186 strncpy(q->sound_minutes, "queue-minutes", sizeof(q->sound_minutes) - 1);
2187 strncpy(q->sound_seconds, "queue-seconds", sizeof(q->sound_seconds) - 1);
2188 strncpy(q->sound_thanks, "queue-thankyou", sizeof(q->sound_thanks) - 1);
2189 strncpy(q->sound_lessthan, "queue-less-than", sizeof(q->sound_lessthan) - 1);
2190 strncpy(q->sound_reporthold, "queue-reporthold", sizeof(q->sound_reporthold) - 1);
2193 /* find the end of any dynamic members */
2197 var = ast_variable_browse(cfg, cat);
2199 if (!strcasecmp(var->name, "member")) {
2200 /* Add a new member */
2201 cur = malloc(sizeof(struct member));
2203 memset(cur, 0, sizeof(struct member));
2204 strncpy(cur->interface, var->value, sizeof(cur->interface) - 1);
2205 if ((tmp = strchr(cur->interface, ','))) {
2208 cur->penalty = atoi(tmp);
2209 if (cur->penalty < 0)
2212 if (!strchr(cur->interface, '/'))
2213 ast_log(LOG_WARNING, "No location at line %d of queue.conf\n", var->lineno);
2220 } else if (!strcasecmp(var->name, "music") || !strcasecmp(var->name, "musiconhold")) {
2221 strncpy(q->moh, var->value, sizeof(q->moh) - 1);
2222 } else if (!strcasecmp(var->name, "announce")) {
2223 strncpy(q->announce, var->value, sizeof(q->announce) - 1);
2224 } else if (!strcasecmp(var->name, "context")) {
2225 strncpy(q->context, var->value, sizeof(q->context) - 1);
2226 } else if (!strcasecmp(var->name, "timeout")) {
2227 q->timeout = atoi(var->value);
2228 } else if (!strcasecmp(var->name, "monitor-join")) {
2229 ast_set2_flag(q, ast_true(var->value), QUEUE_FLAG_MONJOIN);
2230 } else if (!strcasecmp(var->name, "monitor-format")) {
2231 strncpy(q->monfmt, var->value, sizeof(q->monfmt) - 1);
2232 } else if (!strcasecmp(var->name, "queue-youarenext")) {
2233 strncpy(q->sound_next, var->value, sizeof(q->sound_next) - 1);
2234 } else if (!strcasecmp(var->name, "queue-thereare")) {
2235 strncpy(q->sound_thereare, var->value, sizeof(q->sound_thereare) - 1);
2236 } else if (!strcasecmp(var->name, "queue-callswaiting")) {
2237 strncpy(q->sound_calls, var->value, sizeof(q->sound_calls) - 1);
2238 } else if (!strcasecmp(var->name, "queue-holdtime")) {
2239 strncpy(q->sound_holdtime, var->value, sizeof(q->sound_holdtime) - 1);
2240 } else if (!strcasecmp(var->name, "queue-minutes")) {
2241 strncpy(q->sound_minutes, var->value, sizeof(q->sound_minutes) - 1);
2242 } else if (!strcasecmp(var->name, "queue-seconds")) {
2243 strncpy(q->sound_seconds, var->value, sizeof(q->sound_seconds) - 1);
2244 } else if (!strcasecmp(var->name, "queue-lessthan")) {
2245 strncpy(q->sound_lessthan, var->value, sizeof(q->sound_lessthan) - 1);
2246 } else if (!strcasecmp(var->name, "queue-thankyou")) {
2247 strncpy(q->sound_thanks, var->value, sizeof(q->sound_thanks) - 1);
2248 } else if (!strcasecmp(var->name, "queue-reporthold")) {
2249 strncpy(q->sound_reporthold, var->value, sizeof(q->sound_reporthold) - 1);
2250 } else if (!strcasecmp(var->name, "announce-frequency")) {
2251 q->announcefrequency = atoi(var->value);
2252 } else if (!strcasecmp(var->name, "announce-round-seconds")) {
2253 q->roundingseconds = atoi(var->value);
2254 if(q->roundingseconds>60 || q->roundingseconds<0) {
2255 ast_log(LOG_WARNING, "'%s' isn't a valid value for queue-rounding-seconds using 0 instead at line %d of queue.conf\n", var->value, var->lineno);
2256 q->roundingseconds=0;
2258 } else if (!strcasecmp(var->name, "announce-holdtime")) {
2259 q->announceholdtime = (!strcasecmp(var->value,"once")) ? 1 : ast_true(var->value);
2260 } else if (!strcasecmp(var->name, "retry")) {
2261 q->retry = atoi(var->value);
2262 } else if (!strcasecmp(var->name, "wrapuptime")) {
2263 q->wrapuptime = atoi(var->value);
2264 } else if (!strcasecmp(var->name, "maxlen")) {
2265 q->maxlen = atoi(var->value);
2266 } else if (!strcasecmp(var->name, "servicelevel")) {
2267 q->servicelevel= atoi(var->value);
2268 } else if (!strcasecmp(var->name, "strategy")) {
2269 q->strategy = strat2int(var->value);
2270 if (q->strategy < 0) {
2271 ast_log(LOG_WARNING, "'%s' isn't a valid strategy, using ringall instead\n", var->value);
2274 } else if (!strcasecmp(var->name, "joinempty")) {
2275 ast_set2_flag(q, ast_true(var->value), QUEUE_FLAG_JOINEMPTY);
2276 } else if (!strcasecmp(var->name, "leavewhenempty")) {
2277 ast_set2_flag(q, ast_true(var->value), QUEUE_FLAG_LEAVEWHENEMPTY);
2278 } else if (!strcasecmp(var->name, "eventwhencalled")) {
2279 ast_set2_flag(q, ast_true(var->value), QUEUE_FLAG_EVENTWHENCALLED);
2280 } else if (!strcasecmp(var->name, "reportholdtime")) {
2281 ast_set2_flag(q, ast_true(var->value), QUEUE_FLAG_REPORTHOLDTIME);
2282 } else if (!strcasecmp(var->name, "memberdelay")) {
2283 q->memberdelay = atoi(var->value);
2285 ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queue.conf\n", cat, var->name, var->lineno);
2290 q->retry = DEFAULT_RETRY;
2292 q->timeout = DEFAULT_TIMEOUT;
2296 ast_mutex_unlock(&q->lock);
2303 /* Initialize global settings */
2304 queue_persistent_members = 0;
2305 if ((general_val = ast_variable_retrieve(cfg, "general", "persistentmembers")))
2306 queue_persistent_members = ast_true(general_val);
2308 cat = ast_category_browse(cfg, cat);
2315 if (ast_test_flag(q, QUEUE_FLAG_DEAD)) {
2323 ast_log(LOG_WARNING, "XXX Leaking a little memory :( XXX\n");
2325 for (cur = q->members; cur; cur = cur->next)
2326 cur->status = ast_device_state(cur->interface);
2331 ast_mutex_unlock(&qlock);
2334 static char *status2str(int status, char *buf, int buflen)
2337 case AST_DEVICE_UNKNOWN:
2338 strncpy(buf, "unknown", buflen - 1);
2340 case AST_DEVICE_NOT_INUSE:
2341 strncpy(buf, "notinuse", buflen - 1);
2343 case AST_DEVICE_INUSE:
2344 strncpy(buf, "inuse", buflen - 1);
2346 case AST_DEVICE_BUSY:
2347 strncpy(buf, "busy", buflen - 1);
2349 case AST_DEVICE_INVALID:
2350 strncpy(buf, "invalid", buflen - 1);
2352 case AST_DEVICE_UNAVAILABLE:
2353 strncpy(buf, "unavailable", buflen - 1);
2356 snprintf(buf, buflen, "unknown status %d", status);
2361 static int __queues_show(int fd, int argc, char **argv, int queue_show)
2363 struct ast_call_queue *q;
2364 struct queue_ent *qe;
2369 char calls[80] = "";
2370 char tmpbuf[80] = "";
2374 if ((!queue_show && argc != 2) || (queue_show && argc != 3))
2375 return RESULT_SHOWUSAGE;
2376 ast_mutex_lock(&qlock);
2379 ast_mutex_unlock(&qlock);
2381 ast_cli(fd, "No such queue: %s.\n",argv[2]);
2383 ast_cli(fd, "No queues.\n");
2384 return RESULT_SUCCESS;
2387 ast_mutex_lock(&q->lock);
2389 if (strcasecmp(q->name, argv[2]) != 0) {
2390 ast_mutex_unlock(&q->lock);
2393 ast_cli(fd, "No such queue: %s.\n",argv[2]);
2400 snprintf(max, sizeof(max), "%d", q->maxlen);
2402 strncpy(max, "unlimited", sizeof(max) - 1);
2404 if(q->callscompleted > 0)
2405 sl = 100*((float)q->callscompletedinsl/(float)q->callscompleted);
2406 ast_cli(fd, "%-12.12s has %d calls (max %s) in '%s' strategy (%ds holdtime), C:%d, A:%d, SL:%2.1f%% within %ds\n",
2407 q->name, q->count, max, int2strat(q->strategy), q->holdtime, q->callscompleted, q->callsabandoned,sl,q->servicelevel);
2409 ast_cli(fd, " Members: \n");
2410 for (mem = q->members; mem; mem = mem->next) {
2412 snprintf(max, sizeof(max) - 20, " with penalty %d", mem->penalty);
2416 strncat(max, " (dynamic)", sizeof(max) - strlen(max) - 1);
2418 snprintf(max + strlen(max), sizeof(max) - strlen(max), " (%s)", status2str(mem->status, tmpbuf, sizeof(tmpbuf)));
2420 snprintf(calls, sizeof(calls), " has taken %d calls (last was %ld secs ago)",
2421 mem->calls, (long)(time(NULL) - mem->lastcall));
2423 strncpy(calls, " has taken no calls yet", sizeof(calls) - 1);
2424 ast_cli(fd, " %s%s%s\n", mem->interface, max, calls);
2427 ast_cli(fd, " No Members\n");
2430 ast_cli(fd, " Callers: \n");
2431 for (qe = q->head; qe; qe = qe->next)
2432 ast_cli(fd, " %d. %s (wait: %ld:%2.2ld, prio: %d)\n", pos++, qe->chan->name,
2433 (long)(now - qe->start) / 60, (long)(now - qe->start) % 60, qe->prio);
2435 ast_cli(fd, " No Callers\n");
2437 ast_mutex_unlock(&q->lock);
2442 ast_mutex_unlock(&qlock);
2443 return RESULT_SUCCESS;
2446 static int queues_show(int fd, int argc, char **argv)
2448 return __queues_show(fd, argc, argv, 0);
2451 static int queue_show(int fd, int argc, char **argv)
2453 return __queues_show(fd, argc, argv, 1);
2456 static char *complete_queue(char *line, char *word, int pos, int state)
2458 struct ast_call_queue *q;
2461 ast_mutex_lock(&qlock);
2462 for (q = queues; q; q = q->next) {
2463 if (!strncasecmp(word, q->name, strlen(word))) {
2464 if (++which > state)
2468 ast_mutex_unlock(&qlock);
2469 return q ? strdup(q->name) : NULL;
2472 /* JDG: callback to display queues status in manager */
2473 static int manager_queues_show( struct mansession *s, struct message *m )
2475 char *a[] = { "show", "queues" };
2476 return queues_show(s->fd, 2, a);
2480 /* Dump queue status */
2481 static int manager_queues_status( struct mansession *s, struct message *m )
2485 char *id = astman_get_header(m,"ActionID");
2486 char idText[256] = "";
2487 struct ast_call_queue *q;
2488 struct queue_ent *qe;
2492 astman_send_ack(s, m, "Queue status will follow");
2494 ast_mutex_lock(&qlock);
2495 if (!ast_strlen_zero(id)) {
2496 snprintf(idText,256,"ActionID: %s\r\n",id);
2498 for (q = queues; q; q = q->next) {
2499 ast_mutex_lock(&q->lock);
2501 /* List queue properties */
2502 if(q->callscompleted > 0)
2503 sl = 100*((float)q->callscompletedinsl/(float)q->callscompleted);
2504 ast_mutex_lock(&s->lock);
2505 ast_cli(s->fd, "Event: QueueParams\r\n"
2512 "ServiceLevel: %d\r\n"
2513 "ServicelevelPerf: %2.1f\r\n"
2516 q->name, q->maxlen, q->count, q->holdtime, q->callscompleted,
2517 q->callsabandoned, q->servicelevel, sl, idText);
2519 /* List Queue Members */
2520 for (mem = q->members; mem; mem = mem->next)
2521 ast_cli(s->fd, "Event: QueueMember\r\n"
2524 "Membership: %s\r\n"
2526 "CallsTaken: %d\r\n"
2531 q->name, mem->interface, mem->dynamic ? "dynamic" : "static",
2532 mem->penalty, mem->calls, mem->lastcall, mem->status, idText);
2534 /* List Queue Entries */
2537 for (qe = q->head; qe; qe = qe->next)
2538 ast_cli(s->fd, "Event: QueueEntry\r\n"
2543 "CallerIDName: %s\r\n"
2547 q->name, pos++, qe->chan->name,
2548 qe->chan->cid.cid_num ? qe->chan->cid.cid_num : "unknown",
2549 qe->chan->cid.cid_name ? qe->chan->cid.cid_name : "unknown",
2550 (long)(now - qe->start), idText);
2551 ast_mutex_unlock(&s->lock);
2552 ast_mutex_unlock(&q->lock);
2554 ast_mutex_unlock(&qlock);
2555 return RESULT_SUCCESS;
2558 static int manager_add_queue_member(struct mansession *s, struct message *m)
2560 char *queuename, *interface, *penalty_s;
2563 queuename = astman_get_header(m, "Queue");
2564 interface = astman_get_header(m, "Interface");
2565 penalty_s = astman_get_header(m, "Penalty");
2567 if (ast_strlen_zero(queuename)) {
2568 astman_send_error(s, m, "'Queue' not specified.");
2572 if (ast_strlen_zero(interface)) {
2573 astman_send_error(s, m, "'Interface' not specified.");
2577 if (ast_strlen_zero(penalty_s))
2579 else if (sscanf(penalty_s, "%d", &penalty) != 1) {
2583 switch (add_to_queue(queuename, interface, penalty)) {
2585 astman_send_ack(s, m, "Added interface to queue");
2588 astman_send_error(s, m, "Unable to add interface: Already there");
2590 case RES_NOSUCHQUEUE:
2591 astman_send_error(s, m, "Unable to add interface to queue: No such queue");
2593 case RES_OUTOFMEMORY:
2594 astman_send_error(s, m, "Out of memory");
2600 static int manager_remove_queue_member(struct mansession *s, struct message *m)
2602 char *queuename, *interface;
2604 queuename = astman_get_header(m, "Queue");
2605 interface = astman_get_header(m, "Interface");
2607 if (ast_strlen_zero(queuename) || ast_strlen_zero(interface)) {
2608 astman_send_error(s, m, "Need 'Queue' and 'Interface' parameters.");
2612 switch (remove_from_queue(queuename, interface)) {
2614 astman_send_ack(s, m, "Removed interface from queue");
2617 astman_send_error(s, m, "Unable to remove interface: Not there");
2619 case RES_NOSUCHQUEUE:
2620 astman_send_error(s, m, "Unable to remove interface from queue: No such queue");
2622 case RES_OUTOFMEMORY:
2623 astman_send_error(s, m, "Out of memory");
2629 static int handle_add_queue_member(int fd, int argc, char *argv[])
2631 char *queuename, *interface;
2634 if ((argc != 6) && (argc != 8)) {
2635 return RESULT_SHOWUSAGE;
2636 } else if (strcmp(argv[4], "to")) {
2637 return RESULT_SHOWUSAGE;
2638 } else if ((argc == 8) && strcmp(argv[6], "penalty")) {
2639 return RESULT_SHOWUSAGE;
2642 queuename = argv[5];
2643 interface = argv[3];
2645 if (sscanf(argv[7], "%d", &penalty) == 1) {
2647 ast_cli(fd, "Penalty must be >= 0\n");
2651 ast_cli(fd, "Penalty must be an integer >= 0\n");
2658 switch (add_to_queue(queuename, interface, penalty)) {
2660 ast_cli(fd, "Added interface '%s' to queue '%s'\n", interface, queuename);
2661 return RESULT_SUCCESS;
2663 ast_cli(fd, "Unable to add interface '%s' to queue '%s': Already there\n", interface, queuename);
2664 return RESULT_FAILURE;
2665 case RES_NOSUCHQUEUE:
2666 ast_cli(fd, "Unable to add interface to queue '%s': No such queue\n", queuename);
2667 return RESULT_FAILURE;
2668 case RES_OUTOFMEMORY:
2669 ast_cli(fd, "Out of memory\n");
2670 return RESULT_FAILURE;
2672 return RESULT_FAILURE;
2676 static char *complete_add_queue_member(char *line, char *word, int pos, int state)
2678 /* 0 - add; 1 - queue; 2 - member; 3 - <member>; 4 - to; 5 - <queue>; 6 - penalty; 7 - <penalty> */
2681 /* Don't attempt to complete name of member (infinite possibilities) */
2685 return strdup("to");
2690 /* No need to duplicate code */
2691 return complete_queue(line, word, pos, state);
2694 return strdup("penalty");
2699 if (state < 100) { /* 0-99 */
2700 char *num = malloc(3);
2702 sprintf(num, "%d", state);
2713 static int handle_remove_queue_member(int fd, int argc, char *argv[])
2715 char *queuename, *interface;
2718 return RESULT_SHOWUSAGE;
2719 } else if (strcmp(argv[4], "from")) {
2720 return RESULT_SHOWUSAGE;
2723 queuename = argv[5];
2724 interface = argv[3];
2726 switch (remove_from_queue(queuename, interface)) {
2728 ast_cli(fd, "Removed interface '%s' from queue '%s'\n", interface, queuename);
2729 return RESULT_SUCCESS;
2731 ast_cli(fd, "Unable to remove interface '%s' from queue '%s': Not there\n", interface, queuename);
2732 return RESULT_FAILURE;
2733 case RES_NOSUCHQUEUE:
2734 ast_cli(fd, "Unable to remove interface from queue '%s': No such queue\n", queuename);
2735 return RESULT_FAILURE;
2736 case RES_OUTOFMEMORY:
2737 ast_cli(fd, "Out of memory\n");
2738 return RESULT_FAILURE;
2740 return RESULT_FAILURE;
2744 static char *complete_remove_queue_member(char *line, char *word, int pos, int state)
2747 struct ast_call_queue *q;
2750 /* 0 - add; 1 - queue; 2 - member; 3 - <member>; 4 - to; 5 - <queue> */
2751 if ((pos > 5) || (pos < 3)) {
2756 return strdup("from");
2763 /* No need to duplicate code */
2764 return complete_queue(line, word, pos, state);
2767 if (queues != NULL) {
2768 for (q = queues ; q ; q = q->next) {
2769 ast_mutex_lock(&q->lock);
2770 for (m = q->members ; m ; m = m->next) {
2771 if (++which > state) {
2772 ast_mutex_unlock(&q->lock);
2773 return strdup(m->interface);
2776 ast_mutex_unlock(&q->lock);
2782 static char show_queues_usage[] =
2783 "Usage: show queues\n"
2784 " Provides summary information on call queues.\n";
2786 static struct ast_cli_entry cli_show_queues = {