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 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"
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";
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"
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"
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;
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. */
162 struct ast_channel *chan;
168 int allowredirect_in;
169 int allowredirect_out;
173 int allowdisconnect_in;
174 int allowdisconnect_out;
176 struct member *member;
177 struct localuser *next;
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 */
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 */
210 struct ast_call_queue {
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) */
237 int count; /* How many entries are in the queue */
238 int maxlen; /* Max number of entries in queue */
239 int wrapuptime; /* Wrapup Time */
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 */
245 /* Queue strategy things */
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 */
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 */
260 static struct ast_call_queue *queues = NULL;
261 AST_MUTEX_DEFINE_STATIC(qlock);
263 static char *int2strat(int strategy)
266 for (x=0;x<sizeof(strategies) / sizeof(strategies[0]);x++) {
267 if (strategy == strategies[x].strategy)
268 return strategies[x].name;
273 static int strat2int(char *strategy)
276 for (x=0;x<sizeof(strategies) / sizeof(strategies[0]);x++) {
277 if (!strcasecmp(strategy, strategies[x].name))
278 return strategies[x].strategy;
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)
287 struct queue_ent *cur;
304 static int has_no_members(struct ast_call_queue *q)
306 struct member *member;
309 while(empty && member) {
310 switch(member->status) {
311 case AST_DEVICE_UNAVAILABLE:
312 case AST_DEVICE_INVALID:
313 /* Not logged on, etc */
319 member = member->next;
329 static void *changethread(void *data)
331 struct ast_call_queue *q;
332 struct statechange *sc = data;
335 loc = strchr(sc->dev, '/');
340 ast_log(LOG_WARNING, "Can't change device with no technology!\n");
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);
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",
356 "Location: %s/%s\r\n"
362 q->name, cur->tech, cur->loc, cur->dynamic ? "dynamic" : "static",
363 cur->penalty, cur->calls, cur->lastcall, cur->status);
368 ast_mutex_unlock(&q->lock);
370 ast_mutex_unlock(&qlock);
371 ast_log(LOG_DEBUG, "Device '%s/%s' changed to state '%d'\n", sc->dev, loc, sc->state);
376 static int statechange_queue(const char *dev, int state, void *ign)
378 /* Avoid potential for deadlocks by spawning a new thread to handle
380 struct statechange *sc;
383 sc = malloc(sizeof(struct statechange) + strlen(dev) + 1);
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");
397 static int join_queue(char *queuename, struct queue_ent *qe)
399 struct ast_call_queue *q;
400 struct queue_ent *cur, *prev = NULL;
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
413 * Take into account the priority of the calling user */
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);
429 /* No luck, join at the end of the queue */
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);
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",
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 );
444 ast_log(LOG_NOTICE, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, qe->chan->name, qe->pos );
447 ast_mutex_unlock(&q->lock);
451 ast_mutex_unlock(&qlock);
455 static void free_members(struct ast_call_queue *q, int all)
457 /* Free non-dynamic members */
458 struct member *curm, *next, *prev;
463 if (all || !curm->dynamic) {
475 static void destroy_queue(struct ast_call_queue *q)
477 struct ast_call_queue *cur, *prev = NULL;
478 ast_mutex_lock(&qlock);
479 for (cur = queues; cur; cur = cur->next) {
482 prev->next = cur->next;
489 ast_mutex_unlock(&qlock);
491 ast_mutex_destroy(&q->lock);
495 static int play_file(struct ast_channel *chan, char *filename)
499 ast_stopstream(chan);
500 res = ast_streamfile(chan, filename, chan->language);
503 res = ast_waitstream(chan, "");
508 ast_log(LOG_WARNING, "ast_streamfile failed on %s \n", chan->name);
511 ast_stopstream(chan);
516 static int say_position(struct queue_ent *qe)
518 int res = 0, avgholdmins, avgholdsecs;
521 /* Check to see if this is ludicrous -- if we just announced position, don't do it again*/
523 if ( (now - qe->last_pos) < 15 )
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) )
530 ast_moh_stop(qe->chan);
531 /* Say we're next, if we are */
533 res += play_file(qe->chan, qe->parent->sound_next);
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);
540 /* Round hold time to nearest minute */
541 avgholdmins = abs(( (qe->parent->holdtime + 30) - (now - qe->start) ) / 60);
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;
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);
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);
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);
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);
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);
574 /* Set our last_pos indicators */
576 qe->last_pos_said = qe->pos;
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);
586 static void record_abandoned(struct queue_ent *qe)
588 ast_mutex_lock(&qe->parent->lock);
589 qe->parent->callsabandoned++;
590 ast_mutex_unlock(&qe->parent->lock);
593 static void recalc_holdtime(struct queue_ent *qe)
595 int oldvalue, newvalue;
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 */
601 newvalue = time(NULL) - qe->start;
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);
612 static void leave_queue(struct queue_ent *qe)
614 struct ast_call_queue *q;
615 struct queue_ent *cur, *prev = NULL;
620 ast_mutex_lock(&q->lock);
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);
633 ast_log(LOG_NOTICE, "Queue '%s' Leave, Channel '%s'\n", q->name, qe->chan->name );
635 /* Take us out of the queue */
637 prev->next = cur->next;
641 /* Renumber the people after us in the queue based on a new count */
647 ast_mutex_unlock(&q->lock);
648 if (q->dead && !q->count) {
649 /* It's dead and nobody is in it, so kill it */
654 static void hanguptree(struct localuser *outgoing, struct ast_channel *exception)
656 /* Hang up a tree of stuff */
657 struct localuser *oo;
659 /* Hangup any existing lines we have open */
660 if (outgoing->chan && (outgoing->chan != exception))
661 ast_hangup(outgoing->chan);
663 outgoing=outgoing->next;
668 static int update_status(struct ast_call_queue *q, struct member *member, int status)
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);
677 cur->status = status;
678 manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
680 "Location: %s/%s\r\n"
686 q->name, cur->tech, cur->loc, cur->dynamic ? "dynamic" : "static",
687 cur->penalty, cur->calls, cur->lastcall, cur->status);
693 ast_mutex_unlock(&q->lock);
697 static int update_dial_status(struct ast_call_queue *q, struct member *member, int status)
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;
706 status = AST_DEVICE_UNKNOWN;
707 return update_status(q, member, status);
710 static int ring_entry(struct queue_ent *qe, struct localuser *tmp)
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);
717 ast_cdr_busy(qe->chan->cdr);
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 */
725 ast_log(LOG_NOTICE, "Unable to create channel of type '%s'\n", cur->tech);
728 ast_cdr_busy(qe->chan->cdr);
730 update_dial_status(qe->parent, tmp->member, status);
732 } else if (status != tmp->oldstatus)
733 update_dial_status(qe->parent, tmp->member, status);
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);
758 /* Again, keep going even if there's an error */
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);
768 if (qe->parent->eventwhencalled) {
769 manager_event(EVENT_FLAG_AGENT, "AgentCalled",
770 "AgentCalled: %s/%s\r\n"
771 "ChannelCalling: %s\r\n"
773 "CallerIDName: %s\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);
782 if (option_verbose > 2)
783 ast_verbose(VERBOSE_PREFIX_3 "Called %s/%s\n", tmp->tech, tmp->numsubst);
788 static int ring_one(struct queue_ent *qe, struct localuser *outgoing)
790 struct localuser *cur;
791 struct localuser *best;
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;
806 if (!qe->parent->strategy) {
807 /* Ring everyone who shares this best metric (for ringall) */
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);
817 /* Ring just the best channel */
819 ast_log(LOG_DEBUG, "Trying '%s/%s' with metric %d\n",
820 best->tech, best->numsubst, best->metric);
821 ring_entry(qe, best);
824 } while (best && !best->chan);
827 ast_log(LOG_DEBUG, "Nobody left to try ringing in queue\n");
833 static int store_next(struct queue_ent *qe, struct localuser *outgoing)
835 struct localuser *cur;
836 struct localuser *best;
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;
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;
854 /* Just increment rrpos */
855 if (!qe->parent->wrapped) {
856 /* No more channels, start over */
857 qe->parent->rrpos = 0;
859 /* Prioritize next entry */
863 qe->parent->wrapped = 0;
867 static int valid_exit(struct queue_ent *qe, char digit)
870 if (ast_strlen_zero(qe->context))
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;
883 #define AST_MAX_WATCHERS 256
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)
887 char *queue = qe->parent->name;
897 struct localuser *peer = NULL;
898 struct ast_channel *watchers[AST_MAX_WATCHERS];
900 struct ast_channel *winner;
901 struct ast_channel *in = qe->chan;
903 while(*to && !peer) {
910 /* Keep track of important channels */
911 if (o->stillgoing && o->chan) {
912 watchers[pos++] = o->chan;
919 if (numlines == (numbusies + numnochan)) {
920 ast_log(LOG_DEBUG, "Everyone is busy at this time\n");
922 ast_log(LOG_NOTICE, "No one is answering queue '%s'\n", queue);
927 winner = ast_waitfor_n(watchers, pos, to);
930 if (o->stillgoing && (o->chan) && (o->chan->_state == AST_STATE_UP)) {
932 if (option_verbose > 2)
933 ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
935 *allowredir_in = o->allowredirect_in;
936 *allowredir_out = o->allowredirect_out;
937 *allowdisconnect_in = o->allowdisconnect_in;
938 *allowdisconnect_out = o->allowdisconnect_out;
940 } else if (o->chan && (o->chan == winner)) {
941 if (!ast_strlen_zero(o->chan->call_forward)) {
942 char tmpchan[256]="";
945 strncpy(tmpchan, o->chan->call_forward, sizeof(tmpchan) - 1);
946 if ((stuff = strchr(tmpchan, '/'))) {
951 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", o->chan->call_forward, o->chan->context);
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);
963 ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s'\n", tech, stuff);
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;
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");
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");
984 strncpy(o->chan->accountcode, in->accountcode, sizeof(o->chan->accountcode) - 1);
985 o->chan->cdrflags = in->cdrflags;
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);
994 ast_log(LOG_WARNING, "Out of memory\n");
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);
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);
1005 ast_hangup(o->chan);
1010 /* Hangup the original channel now, in case we needed it */
1014 f = ast_read(winner);
1016 if (f->frametype == AST_FRAME_CONTROL) {
1017 switch(f->subclass) {
1018 case AST_CONTROL_ANSWER:
1019 /* This is our guy if someone answered. */
1021 if (option_verbose > 2)
1022 ast_verbose( VERBOSE_PREFIX_3 "%s answered %s\n", o->chan->name, in->name);
1024 *allowredir_in = o->allowredirect_in;
1025 *allowredir_out = o->allowredirect_out;
1026 *allowdisconnect_in = o->allowdisconnect_out;
1027 *allowdisconnect_out = o->allowdisconnect_out;
1030 case AST_CONTROL_BUSY:
1031 if (option_verbose > 2)
1032 ast_verbose( VERBOSE_PREFIX_3 "%s is busy\n", o->chan->name);
1035 ast_cdr_busy(in->cdr);
1036 ast_hangup(o->chan);
1038 if (qe->parent->strategy)
1039 ring_one(qe, outgoing);
1042 case AST_CONTROL_CONGESTION:
1043 if (option_verbose > 2)
1044 ast_verbose( VERBOSE_PREFIX_3 "%s is circuit-busy\n", o->chan->name);
1047 ast_cdr_busy(in->cdr);
1048 ast_hangup(o->chan);
1050 if (qe->parent->strategy)
1051 ring_one(qe, outgoing);
1054 case AST_CONTROL_RINGING:
1055 if (option_verbose > 2)
1056 ast_verbose( VERBOSE_PREFIX_3 "%s is ringing\n", o->chan->name);
1059 ast_indicate(in, AST_CONTROL_RINGING);
1064 case AST_CONTROL_OFFHOOK:
1065 /* Ignore going off hook */
1068 ast_log(LOG_DEBUG, "Dunno what to do with control type %d\n", f->subclass);
1074 ast_hangup(o->chan);
1076 if (qe->parent->strategy)
1077 ring_one(qe, outgoing);
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);
1090 if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))) {
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);
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);
1109 if (!*to && (option_verbose > 2))
1110 ast_verbose( VERBOSE_PREFIX_3 "Nobody picked up in %d ms\n", orig);
1117 static int is_our_turn(struct queue_ent *qe)
1119 struct queue_ent *ch;
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 */
1127 ast_log(LOG_DEBUG, "It's our turn (%s).\n", qe->chan->name);
1131 ast_log(LOG_DEBUG, "It's not our turn (%s).\n", qe->chan->name);
1137 static int wait_our_turn(struct queue_ent *qe, int ringing)
1139 struct queue_ent *ch;
1143 /* This is the holding pen for callers 2 through maxlen */
1145 /* Atomically read the parent head -- does not need a lock */
1146 ch = qe->parent->head;
1148 /* If we are now at the top of the head, break out */
1151 ast_log(LOG_DEBUG, "It's our turn (%s).\n", qe->chan->name);
1155 /* If we have timed out, break out */
1156 if ( qe->queuetimeout ) {
1158 if ( (now - qe->start) >= qe->queuetimeout )
1162 /* leave the queue if no agents, if enabled */
1163 if (has_no_members(qe->parent) && qe->parent->leavewhenempty) {
1168 /* Make a position announcement, if enabled */
1169 if (qe->parent->announcefrequency && !ringing)
1172 /* Wait a second before checking again */
1173 res = ast_waitfordigit(qe->chan, RECHECK * 1000);
1180 static int update_queue(struct ast_call_queue *q, struct member *member)
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);
1188 if (member == cur) {
1189 time(&cur->lastcall);
1195 q->callscompleted++;
1196 ast_mutex_unlock(&q->lock);
1200 static int calc_metric(struct ast_call_queue *q, struct member *mem, int pos, struct queue_ent *qe, struct localuser *tmp)
1202 switch (q->strategy) {
1203 case QUEUE_STRATEGY_RINGALL:
1204 /* Everyone equal, except for penalty */
1205 tmp->metric = mem->penalty * 1000000;
1207 case QUEUE_STRATEGY_ROUNDROBIN:
1210 /* No more channels, start over */
1213 /* Prioritize next entry */
1219 case QUEUE_STRATEGY_RRMEMORY:
1220 if (pos < q->rrpos) {
1221 tmp->metric = 1000 + pos;
1223 if (pos > q->rrpos) {
1224 /* Indicate there is another priority */
1229 tmp->metric += mem->penalty * 1000000;
1231 case QUEUE_STRATEGY_RANDOM:
1232 tmp->metric = rand() % 1000;
1233 tmp->metric += mem->penalty * 1000000;
1235 case QUEUE_STRATEGY_FEWESTCALLS:
1236 tmp->metric = mem->calls;
1237 tmp->metric += mem->penalty * 1000000;
1239 case QUEUE_STRATEGY_LEASTRECENT:
1243 tmp->metric = 1000000 - (time(NULL) - mem->lastcall);
1244 tmp->metric += mem->penalty * 1000000;
1247 ast_log(LOG_WARNING, "Can't calculate metric for unknown strategy %d\n", q->strategy);
1253 static int try_calling(struct queue_ent *qe, char *options, char *announceoverride, char *url, int *go_on)
1256 struct localuser *outgoing=NULL, *tmp = NULL;
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]="";
1267 char *monitorfilename;
1268 struct ast_channel *peer;
1269 struct localuser *lpeer;
1270 struct member *member;
1271 int res = 0, bridge = 0;
1274 char *announce = NULL;
1278 struct ast_bridge_config config;
1279 /* Hold the lock while we setup the outgoing calls */
1280 ast_mutex_lock(&qe->parent->lock);
1282 ast_log(LOG_DEBUG, "%s is trying to call a queue member.\n",
1284 strncpy(queuename, qe->parent->name, sizeof(queuename) - 1);
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;
1292 /* Get a technology/[device:]number pair */
1293 tmp = malloc(sizeof(struct localuser));
1295 ast_mutex_unlock(&qe->parent->lock);
1296 ast_log(LOG_WARNING, "Out of memory\n");
1299 memset(tmp, 0, sizeof(struct localuser));
1300 tmp->stillgoing = -1;
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))
1321 ast_log(LOG_DEBUG, "Queue with URL=%s_\n", url);
1323 ast_log(LOG_DEBUG, "Simple queue (no URL)\n");
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);
1336 ast_log(LOG_DEBUG, "Dialing by extension %s\n", tmp->numsubst);
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
1344 tmp->next = outgoing;
1346 /* If this line is up, don't try anybody else */
1347 if (outgoing->chan && (outgoing->chan->_state == AST_STATE_UP))
1352 if (qe->parent->timeout)
1353 to = qe->parent->timeout * 1000;
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);
1363 ast_mutex_unlock(&qe->parent->lock);
1370 /* Musta gotten hung up */
1371 record_abandoned(qe);
1374 if (digit && valid_exit(qe, digit))
1377 /* Nobody answered, next please? */
1381 ast_log(LOG_DEBUG, "%s: Nobody answered.\n", qe->chan->name);
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
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);
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);
1397 /* Update parameters for the queue */
1398 recalc_holdtime(qe);
1399 member = lpeer->member;
1400 hanguptree(outgoing, peer);
1402 if (announce || qe->parent->reportholdtime || qe->parent->memberdelay) {
1404 res2 = ast_autoservice_start(qe->chan);
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);
1410 if (!res2 && announce) {
1411 if (play_file(peer, announce))
1412 ast_log(LOG_WARNING, "Announcement file '%s' is unavailable, continuing anyway...\n", announce);
1414 if (!res2 && qe->parent->reportholdtime) {
1415 if (!play_file(peer, qe->parent->sound_reporthold)) {
1420 holdtime = abs((now - qe->start) / 60);
1422 play_file(peer, qe->parent->sound_lessthan);
1423 ast_say_number(peer, 2, AST_DIGIT_ANY, peer->language, NULL);
1425 ast_say_number(peer, holdtime, AST_DIGIT_ANY, peer->language, NULL);
1426 play_file(peer, qe->parent->sound_minutes);
1430 res2 |= ast_autoservice_stop(qe->chan);
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", "");
1439 /* Stop music on hold */
1440 ast_moh_stop(qe->chan);
1441 /* If appropriate, log that we have a destination channel */
1443 ast_cdr_setdestchan(qe->chan->cdr, peer->name);
1444 /* Make sure channels are compatible */
1445 res = ast_channel_make_compatible(qe->chan, peer);
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);
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 );
1458 ast_monitor_start( peer, qe->parent->monfmt, qe->chan->cdr->uniqueid, 1 );
1460 if(qe->parent->monjoin) {
1461 ast_monitor_setjoinfiles( peer, 1);
1464 /* Drop out of the queue at this point, to prepare for next caller */
1466 if( url && !ast_strlen_zero(url) && ast_channel_supports_html(peer) ) {
1468 ast_log(LOG_DEBUG, "app_queue: sendurl=%s.\n", url);
1469 ast_channel_sendurl( peer, url );
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);
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);
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));
1488 ast_queue_log(queuename, qe->chan->uniqueid, peer->name, "COMPLETEAGENT", "%ld|%ld", (long)(callstart - qe->start), (long)(time(NULL) - callstart));
1491 if(bridge != AST_PBX_NO_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 */
1498 hanguptree(outgoing, NULL);
1502 static int wait_a_bit(struct queue_ent *qe)
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);
1511 static struct member * interface_exists( struct ast_call_queue * q, char * interface )
1513 struct member * ret = NULL ;
1521 while( mem != NULL ) {
1522 snprintf( buf, sizeof(buf), "%s/%s", mem->tech, mem->loc);
1524 if( strcmp( buf, interface ) == 0 ) {
1537 static struct member * create_queue_node( char * interface, int penalty )
1539 struct member * cur ;
1542 /* Add a new member */
1544 cur = malloc(sizeof(struct member));
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, '/')))
1552 if ((tmp = strchr(interface, '/'))) {
1554 strncpy(cur->loc, tmp, sizeof(cur->loc) - 1);
1556 ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
1557 cur->status = ast_device_state(interface);
1563 /* Dump all members in a specific queue to the databse
1565 * <pm_family>/<queuename> = <interface>;<penalty>;...
1568 static void dump_queue_members(struct ast_call_queue *pm_queue)
1570 struct member *cur_member = NULL;
1571 char value[PM_MAX_LEN];
1575 memset(value, 0, sizeof(value));
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");
1588 cur_member = cur_member->next;
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");
1595 /* Delete the entry if the queue is empty or there is an error */
1596 ast_db_del(pm_family, pm_queue->name);
1603 static int remove_from_queue(char *queuename, char *interface)
1605 struct ast_call_queue *q;
1606 struct member *last_member, *look;
1607 int res = RES_NOSUCHQUEUE;
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;
1617 while (look != NULL) {
1618 if (look->next == last_member) {
1619 look->next = last_member->next;
1626 manager_event(EVENT_FLAG_AGENT, "QueueMemberRemoved",
1628 "Location: %s/%s\r\n",
1629 q->name, last_member->tech, last_member->loc);
1632 if (queue_persistent_members)
1633 dump_queue_members(q);
1639 ast_mutex_unlock(&q->lock);
1642 ast_mutex_unlock(&q->lock);
1644 ast_mutex_unlock(&qlock);
1648 static int add_to_queue(char *queuename, char *interface, int penalty)
1650 struct ast_call_queue *q;
1651 struct member *new_member;
1652 int res = RES_NOSUCHQUEUE;
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);
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",
1667 "Location: %s/%s\r\n"
1668 "Membership: %s\r\n"
1670 "CallsTaken: %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);
1676 if (queue_persistent_members)
1677 dump_queue_members(q);
1681 res = RES_OUTOFMEMORY;
1686 ast_mutex_unlock(&q->lock);
1689 ast_mutex_unlock(&q->lock);
1691 ast_mutex_unlock(&qlock);
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)
1700 char *pm_queue_name;
1702 char *pm_penalty_tok;
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];
1709 pm_db_tree = ast_db_gettree(pm_family, NULL);
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;
1720 ast_mutex_lock(&cur_queue->lock);
1722 if (strcmp(pm_queue_name, cur_queue->name) == 0)
1725 ast_mutex_unlock(&cur_queue->lock);
1727 cur_queue = cur_queue->next;
1731 /* If the queue no longer exists, remove it from the
1733 ast_db_del(pm_family, pm_queue_name);
1734 pm_db_tree = pm_db_tree->next;
1737 ast_mutex_unlock(&cur_queue->lock);
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);
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);
1755 ast_log(LOG_DEBUG, "Reload Members: Queue: %s Member: %s Penalty: %d\n", pm_queue_name, pm_interface, pm_penalty);
1757 if (add_to_queue(pm_queue_name, pm_interface, pm_penalty) == RES_OUTOFMEMORY) {
1758 ast_log(LOG_ERROR, "Out of Memory\n");
1764 pm_db_tree = pm_db_tree->next;
1767 ast_log(LOG_NOTICE, "Queue members sucessfully reloaded from database.\n");
1768 ast_mutex_unlock(&qlock);
1770 ast_db_freetree(pm_db_tree);
1775 static int rqm_exec(struct ast_channel *chan, void *data)
1778 struct localuser *u;
1779 char *info, *queuename;
1780 char tmpchan[256]="";
1781 char *interface = NULL;
1784 ast_log(LOG_WARNING, "RemoveQueueMember requires an argument (queuename[|interface])\n");
1788 info = ast_strdupa((char *)data);
1790 ast_log(LOG_ERROR, "Out of memory\n");
1798 interface = strchr(queuename, '|');
1804 strncpy(tmpchan, chan->name, sizeof(tmpchan) - 1);
1805 interface = strrchr(tmpchan, '-');
1808 interface = tmpchan;
1812 switch (remove_from_queue(queuename, interface)) {
1814 ast_log(LOG_NOTICE, "Removed interface '%s' from queue '%s'\n", interface, queuename);
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;
1824 case RES_NOSUCHQUEUE:
1825 ast_log(LOG_WARNING, "Unable to remove interface from queue '%s': No such queue\n", queuename);
1828 case RES_OUTOFMEMORY:
1829 ast_log(LOG_ERROR, "Out of memory\n");
1833 LOCAL_USER_REMOVE(u);
1837 static int aqm_exec(struct ast_channel *chan, void *data)
1840 struct localuser *u;
1843 char tmpchan[512]="";
1844 char *interface=NULL;
1845 char *penaltys=NULL;
1849 ast_log(LOG_WARNING, "AddQueueMember requires an argument (queuename[|[interface][|penalty]])\n");
1853 info = ast_strdupa((char *)data);
1855 ast_log(LOG_ERROR, "Out of memory\n");
1862 interface = strchr(queuename, '|');
1868 penaltys = strchr(interface, '|');
1874 if (!interface || ast_strlen_zero(interface)) {
1875 strncpy(tmpchan, chan->name, sizeof(tmpchan) - 1);
1876 interface = strrchr(tmpchan, '-');
1879 interface = tmpchan;
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);
1889 switch (add_to_queue(queuename, interface, penalty)) {
1891 ast_log(LOG_NOTICE, "Added interface '%s' to queue '%s'\n", interface, queuename);
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;
1901 case RES_NOSUCHQUEUE:
1902 ast_log(LOG_WARNING, "Unable to add interface to queue '%s': No such queue\n", queuename);
1905 case RES_OUTOFMEMORY:
1906 ast_log(LOG_ERROR, "Out of memory\n");
1910 LOCAL_USER_REMOVE(u);
1914 static int queue_exec(struct ast_channel *chan, void *data)
1918 struct localuser *u;
1921 char *options = NULL;
1923 char *announceoverride = NULL;
1924 char *user_priority;
1926 char *queuetimeoutstr = NULL;
1928 /* whether to exit Queue application after the timeout hits */
1931 /* Our queue entry */
1932 struct queue_ent qe;
1935 ast_log(LOG_WARNING, "Queue requires an argument (queuename[|[timeout][|URL]])\n");
1941 /* Setup our queue entry */
1942 memset(&qe, 0, sizeof(qe));
1944 /* Parse our arguments XXX Check for failure XXX */
1945 strncpy(info, (char *)data, strlen((char *)data) + AST_MAX_EXTENSION-1);
1948 options = strchr(queuename, '|');
1952 url = strchr(options, '|');
1956 announceoverride = strchr(url, '|');
1957 if (announceoverride) {
1958 *announceoverride = '\0';
1960 queuetimeoutstr = strchr(announceoverride, '|');
1961 if (queuetimeoutstr) {
1962 *queuetimeoutstr = '\0';
1964 qe.queuetimeout = atoi(queuetimeoutstr);
1966 qe.queuetimeout = 0;
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) {
1978 ast_log(LOG_DEBUG, "%s: Got priority %d from ${QUEUE_PRIO}.\n",
1981 ast_log(LOG_WARNING, "${QUEUE_PRIO}: Invalid value (%s), channel %s.\n",
1982 user_priority, chan->name);
1987 ast_log(LOG_DEBUG, "NO QUEUE_PRIO variable found. Using default.\n");
1992 if (strchr(options, 'r')) {
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);
2002 qe.start = time(NULL);
2003 qe.prio = (int)prio;
2004 qe.last_pos_said = 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 */
2011 ast_indicate(chan, AST_CONTROL_RINGING);
2013 ast_moh_start(chan, qe.moh);
2016 /* This is the wait loop for callers 2 through maxlen */
2018 res = wait_our_turn(&qe, ringing);
2019 /* If they hungup, return immediately */
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");
2032 if (valid_exit(&qe, res)) {
2033 ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHKEY", "%c|%d", res, qe.pos);
2038 int makeannouncement = 0;
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. */
2045 /* Leave if we have exceeded our queuetimeout */
2046 if (qe.queuetimeout && ( (time(NULL) - qe.start) >= qe.queuetimeout) ) {
2051 if (makeannouncement) {
2052 /* Make a position announcement, if enabled */
2053 if (qe.parent->announcefrequency && !ringing)
2056 makeannouncement = 1;
2058 /* Try calling all queue members for 'timeout' seconds */
2059 res = try_calling(&qe, options, announceoverride, url, &go_on);
2063 ast_queue_log(queuename, chan->uniqueid, "NONE", "ABANDON", "%d|%d|%ld", qe.pos, qe.opos, (long)time(NULL) - qe.start);
2065 ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHKEY", "%c|%d", res, qe.pos);
2069 /* leave the queue if no agents, if enabled */
2070 if (has_no_members(qe.parent) && (qe.parent->leavewhenempty)) {
2075 /* Leave if we have exceeded our queuetimeout */
2076 if (qe.queuetimeout && ( (time(NULL) - qe.start) >= qe.queuetimeout) ) {
2081 /* OK, we didn't get anybody; wait for 'retry' seconds; may get a digit to exit with */
2082 res = wait_a_bit(&qe);
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");
2091 if (res && valid_exit(&qe, res)) {
2092 ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHKEY", "%c|%d", res, qe.pos);
2095 /* exit after 'timeout' cycle if 'n' option enabled */
2097 if (option_verbose > 2) {
2098 ast_verbose(VERBOSE_PREFIX_3 "Exiting on time-out cycle\n");
2101 ast_queue_log(queuename, chan->uniqueid, "NONE", "EXITWITHTIMEOUT", "%d", qe.pos);
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.
2109 if (!is_our_turn(&qe)) {
2110 ast_log(LOG_DEBUG, "Darn priorities, going back in queue (%s)!\n",
2116 /* Don't allow return code > 0 */
2117 if (res >= 0 && res != AST_PBX_KEEPALIVE) {
2120 ast_indicate(chan, -1);
2124 ast_stopstream(chan);
2128 ast_log(LOG_WARNING, "Unable to join queue '%s'\n", queuename);
2131 LOCAL_USER_REMOVE(u);
2135 static void reload_queues(void)
2137 struct ast_call_queue *q, *ql, *qn;
2138 struct ast_config *cfg;
2140 struct ast_variable *var;
2141 struct member *prev, *cur;
2143 char *general_val = NULL;
2145 cfg = ast_load("queues.conf");
2147 ast_log(LOG_NOTICE, "No call queueing config file, so no call queues\n");
2150 ast_mutex_lock(&qlock);
2151 /* Mark all queues as dead for the moment */
2157 /* Chug through config file */
2158 cat = ast_category_browse(cfg, NULL);
2160 if (strcasecmp(cat, "general")) {
2161 /* Look for an existing one */
2164 if (!strcmp(q->name, cat))
2170 q = malloc(sizeof(struct ast_call_queue));
2173 memset(q, 0, sizeof(struct ast_call_queue));
2174 ast_mutex_init(&q->lock);
2175 strncpy(q->name, cat, sizeof(q->name) - 1);
2182 ast_mutex_lock(&q->lock);
2183 /* Re-initialize the queue */
2188 q->announcefrequency = 0;
2189 q->announceholdtime = 0;
2190 q->roundingseconds = 0; /* Default - don't announce seconds */
2192 q->callscompleted = 0;
2193 q->callsabandoned = 0;
2194 q->callscompletedinsl = 0;
2195 q->servicelevel = 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);
2213 /* find the end of any dynamic members */
2217 var = ast_variable_browse(cfg, cat);
2219 if (!strcasecmp(var->name, "member")) {
2220 /* Add a new member */
2221 cur = malloc(sizeof(struct member));
2223 memset(cur, 0, sizeof(struct member));
2224 strncpy(cur->tech, var->value, sizeof(cur->tech) - 1);
2225 if ((tmp = strchr(cur->tech, ','))) {
2228 cur->penalty = atoi(tmp);
2229 if (cur->penalty < 0)
2232 if ((tmp = strchr(cur->tech, '/')))
2234 if ((tmp = strchr(var->value, '/'))) {
2236 strncpy(cur->loc, tmp, sizeof(cur->loc) - 1);
2237 if ((tmp = strchr(cur->loc, ',')))
2240 ast_log(LOG_WARNING, "No location at line %d of queue.conf\n", var->lineno);
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;
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);
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);
2312 ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queue.conf\n", cat, var->name, var->lineno);
2317 q->retry = DEFAULT_RETRY;
2319 q->timeout = DEFAULT_TIMEOUT;
2323 ast_mutex_unlock(&q->lock);
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);
2335 cat = ast_category_browse(cfg, cat);
2350 ast_log(LOG_WARNING, "XXX Leaking a little memory :( XXX\n");
2355 snprintf(tmp, sizeof(tmp), "%s/%s", cur->tech, cur->loc);
2356 cur->status = ast_device_state(tmp);
2363 ast_mutex_unlock(&qlock);
2366 static char *status2str(int status, char *buf, int buflen)
2369 case AST_DEVICE_UNKNOWN:
2370 strncpy(buf, "unknown", buflen - 1);
2372 case AST_DEVICE_NOT_INUSE:
2373 strncpy(buf, "notinuse", buflen - 1);
2375 case AST_DEVICE_INUSE:
2376 strncpy(buf, "inuse", buflen - 1);
2378 case AST_DEVICE_BUSY:
2379 strncpy(buf, "busy", buflen - 1);
2381 case AST_DEVICE_INVALID:
2382 strncpy(buf, "invalid", buflen - 1);
2384 case AST_DEVICE_UNAVAILABLE:
2385 strncpy(buf, "unavailable", buflen - 1);
2388 snprintf(buf, buflen, "unknown status %d", status);
2393 static int __queues_show(int fd, int argc, char **argv, int queue_show)
2395 struct ast_call_queue *q;
2396 struct queue_ent *qe;
2401 char calls[80] = "";
2402 char tmpbuf[80] = "";
2406 if ((!queue_show && argc != 2) || (queue_show && argc != 3))
2407 return RESULT_SHOWUSAGE;
2408 ast_mutex_lock(&qlock);
2411 ast_mutex_unlock(&qlock);
2413 ast_cli(fd, "No such queue: %s.\n",argv[2]);
2415 ast_cli(fd, "No queues.\n");
2416 return RESULT_SUCCESS;
2419 ast_mutex_lock(&q->lock);
2421 if (strcasecmp(q->name, argv[2]) != 0) {
2422 ast_mutex_unlock(&q->lock);
2425 ast_cli(fd, "No such queue: %s.\n",argv[2]);
2432 snprintf(max, sizeof(max), "%d", q->maxlen);
2434 strncpy(max, "unlimited", sizeof(max) - 1);
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);
2441 ast_cli(fd, " Members: \n");
2442 for (mem = q->members; mem; mem = mem->next) {
2444 snprintf(max, sizeof(max) - 20, " with penalty %d", mem->penalty);
2448 strncat(max, " (dynamic)", sizeof(max) - strlen(max) - 1);
2450 snprintf(max + strlen(max), sizeof(max) - strlen(max), " (%s)", status2str(mem->status, tmpbuf, sizeof(tmpbuf)));
2452 snprintf(calls, sizeof(calls), " has taken %d calls (last was %ld secs ago)",
2453 mem->calls, (long)(time(NULL) - mem->lastcall));
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);
2459 ast_cli(fd, " No Members\n");
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);
2467 ast_cli(fd, " No Callers\n");
2469 ast_mutex_unlock(&q->lock);
2474 ast_mutex_unlock(&qlock);
2475 return RESULT_SUCCESS;
2478 static int queues_show(int fd, int argc, char **argv)
2480 return __queues_show(fd, argc, argv, 0);
2483 static int queue_show(int fd, int argc, char **argv)
2485 return __queues_show(fd, argc, argv, 1);
2488 static char *complete_queue(char *line, char *word, int pos, int state)
2490 struct ast_call_queue *q;
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)
2500 ast_mutex_unlock(&qlock);
2501 return q ? strdup(q->name) : NULL;
2504 /* JDG: callback to display queues status in manager */
2505 static int manager_queues_show( struct mansession *s, struct message *m )
2507 char *a[] = { "show", "queues" };
2508 return queues_show( s->fd, 2, a );
2512 /* Dump queue status */
2513 static int manager_queues_status( struct mansession *s, struct message *m )
2517 char *id = astman_get_header(m,"ActionID");
2518 char idText[256] = "";
2519 struct ast_call_queue *q;
2520 struct queue_ent *qe;
2523 astman_send_ack(s, m, "Queue status will follow");
2525 ast_mutex_lock(&qlock);
2526 if (!ast_strlen_zero(id)) {
2527 snprintf(idText,256,"ActionID: %s\r\n",id);
2529 for (q = queues; q; q = q->next) {
2530 ast_mutex_lock(&q->lock);
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"
2543 "ServiceLevel: %d\r\n"
2544 "ServicelevelPerf: %2.1f\r\n"
2547 q->name, q->maxlen, q->count, q->holdtime, q->callscompleted,
2548 q->callsabandoned, q->servicelevel, sl, idText);
2550 /* List Queue Members */
2551 for (mem = q->members; mem; mem = mem->next)
2552 ast_cli(s->fd, "Event: QueueMember\r\n"
2554 "Location: %s/%s\r\n"
2555 "Membership: %s\r\n"
2557 "CallsTaken: %d\r\n"
2562 q->name, mem->tech, mem->loc, mem->dynamic ? "dynamic" : "static",
2563 mem->penalty, mem->calls, mem->lastcall, mem->status, idText);
2565 /* List Queue Entries */
2568 for (qe = q->head; qe; qe = qe->next)
2569 ast_cli(s->fd, "Event: QueueEntry\r\n"
2574 "CallerIDName: %s\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);
2585 ast_mutex_unlock(&qlock);
2586 return RESULT_SUCCESS;
2589 static int manager_add_queue_member(struct mansession *s, struct message *m)
2591 char *queuename, *interface, *penalty_s;
2594 queuename = astman_get_header(m, "Queue");
2595 interface = astman_get_header(m, "Interface");
2596 penalty_s = astman_get_header(m, "Penalty");
2598 if (ast_strlen_zero(queuename)) {
2599 astman_send_error(s, m, "'Queue' not specified.");
2603 if (ast_strlen_zero(interface)) {
2604 astman_send_error(s, m, "'Interface' not specified.");
2608 if (ast_strlen_zero(penalty_s))
2610 else if (sscanf(penalty_s, "%d", &penalty) != 1) {
2614 switch (add_to_queue(queuename, interface, penalty)) {
2616 astman_send_ack(s, m, "Added interface to queue");
2619 astman_send_error(s, m, "Unable to add interface: Already there");
2621 case RES_NOSUCHQUEUE:
2622 astman_send_error(s, m, "Unable to add interface to queue: No such queue");
2624 case RES_OUTOFMEMORY:
2625 astman_send_error(s, m, "Out of memory");
2631 static int manager_remove_queue_member(struct mansession *s, struct message *m)
2633 char *queuename, *interface;
2635 queuename = astman_get_header(m, "Queue");
2636 interface = astman_get_header(m, "Interface");
2638 if (ast_strlen_zero(queuename) || ast_strlen_zero(interface)) {
2639 astman_send_error(s, m, "Need 'Queue' and 'Interface' parameters.");
2643 switch (remove_from_queue(queuename, interface)) {
2645 astman_send_ack(s, m, "Removed interface from queue");
2648 astman_send_error(s, m, "Unable to remove interface: Not there");
2650 case RES_NOSUCHQUEUE:
2651 astman_send_error(s, m, "Unable to remove interface from queue: No such queue");
2653 case RES_OUTOFMEMORY:
2654 astman_send_error(s, m, "Out of memory");
2660 static int handle_add_queue_member(int fd, int argc, char *argv[])
2662 char *queuename, *interface;
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;
2673 queuename = argv[5];
2674 interface = argv[3];
2676 if (sscanf(argv[7], "%d", &penalty) == 1) {
2678 ast_cli(fd, "Penalty must be >= 0\n");
2682 ast_cli(fd, "Penalty must be an integer >= 0\n");
2689 switch (add_to_queue(queuename, interface, penalty)) {
2691 ast_cli(fd, "Added interface '%s' to queue '%s'\n", interface, queuename);
2692 return RESULT_SUCCESS;
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;
2703 return RESULT_FAILURE;
2707 static char *complete_add_queue_member(char *line, char *word, int pos, int state)
2709 /* 0 - add; 1 - queue; 2 - member; 3 - <member>; 4 - to; 5 - <queue>; 6 - penalty; 7 - <penalty> */
2712 /* Don't attempt to complete name of member (infinite possibilities) */
2716 return strdup("to");
2721 /* No need to duplicate code */
2722 return complete_queue(line, word, pos, state);
2725 return strdup("penalty");
2730 if (state < 100) { /* 0-99 */
2731 char *num = malloc(3);
2733 sprintf(num, "%d", state);
2744 static int handle_remove_queue_member(int fd, int argc, char *argv[])
2746 char *queuename, *interface;
2749 return RESULT_SHOWUSAGE;
2750 } else if (strcmp(argv[4], "from")) {
2751 return RESULT_SHOWUSAGE;
2754 queuename = argv[5];
2755 interface = argv[3];
2757 switch (remove_from_queue(queuename, interface)) {
2759 ast_cli(fd, "Removed interface '%s' from queue '%s'\n", interface, queuename);
2760 return RESULT_SUCCESS;
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: