Merged revisions 96102 via svnmerge from
[asterisk/asterisk.git] / apps / app_queue.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief True call queues with optional send URL on answer
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * \arg Config in \ref Config_qu queues.conf
26  *
27  * \par Development notes
28  * \note 2004-11-25: Persistent Dynamic Members added by:
29  *             NetNation Communications (www.netnation.com)
30  *             Kevin Lindsay <kevinl@netnation.com>
31  *
32  *             Each dynamic agent in each queue is now stored in the astdb.
33  *             When asterisk is restarted, each agent will be automatically
34  *             readded into their recorded queues. This feature can be
35  *             configured with the 'persistent_members=<1|0>' setting in the
36  *             '[general]' category in queues.conf. The default is on.
37  *
38  * \note 2004-06-04: Priorities in queues added by inAccess Networks (work funded by Hellas On Line (HOL) www.hol.gr).
39  *
40  * \note These features added by David C. Troy <dave@toad.net>:
41  *    - Per-queue holdtime calculation
42  *    - Estimated holdtime announcement
43  *    - Position announcement
44  *    - Abandoned/completed call counters
45  *    - Failout timer passed as optional app parameter
46  *    - Optional monitoring of calls, started when call is answered
47  *
48  * Patch Version 1.07 2003-12-24 01
49  *
50  * Added servicelevel statistic by Michiel Betel <michiel@betel.nl>
51  * Added Priority jumping code for adding and removing queue members by Jonathan Stanton <asterisk@doilooklikeicare.com>
52  *
53  * Fixed to work with CVS as of 2004-02-25 and released as 1.07a
54  * by Matthew Enger <m.enger@xi.com.au>
55  *
56  * \ingroup applications
57  */
58
59 /*** MODULEINFO
60         <depend>res_monitor</depend>
61  ***/
62
63 #include "asterisk.h"
64
65 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
66
67 #include <sys/time.h>
68 #include <sys/signal.h>
69 #include <netinet/in.h>
70
71 #include "asterisk/lock.h"
72 #include "asterisk/file.h"
73 #include "asterisk/channel.h"
74 #include "asterisk/pbx.h"
75 #include "asterisk/app.h"
76 #include "asterisk/linkedlists.h"
77 #include "asterisk/module.h"
78 #include "asterisk/translate.h"
79 #include "asterisk/say.h"
80 #include "asterisk/features.h"
81 #include "asterisk/musiconhold.h"
82 #include "asterisk/cli.h"
83 #include "asterisk/manager.h"
84 #include "asterisk/config.h"
85 #include "asterisk/monitor.h"
86 #include "asterisk/utils.h"
87 #include "asterisk/causes.h"
88 #include "asterisk/astdb.h"
89 #include "asterisk/devicestate.h"
90 #include "asterisk/stringfields.h"
91 #include "asterisk/event.h"
92 #include "asterisk/astobj2.h"
93 #include "asterisk/strings.h"
94 #include "asterisk/global_datastores.h"
95
96 enum {
97         QUEUE_STRATEGY_RINGALL = 0,
98         QUEUE_STRATEGY_LEASTRECENT,
99         QUEUE_STRATEGY_FEWESTCALLS,
100         QUEUE_STRATEGY_RANDOM,
101         QUEUE_STRATEGY_RRMEMORY,
102         QUEUE_STRATEGY_LINEAR,
103         QUEUE_STRATEGY_WRANDOM
104 };
105
106 static struct strategy {
107         int strategy;
108         char *name;
109 } strategies[] = {
110         { QUEUE_STRATEGY_RINGALL, "ringall" },
111         { QUEUE_STRATEGY_LEASTRECENT, "leastrecent" },
112         { QUEUE_STRATEGY_FEWESTCALLS, "fewestcalls" },
113         { QUEUE_STRATEGY_RANDOM, "random" },
114         { QUEUE_STRATEGY_RRMEMORY, "rrmemory" },
115         { QUEUE_STRATEGY_LINEAR, "linear" },
116         { QUEUE_STRATEGY_WRANDOM, "wrandom"},
117 };
118
119 #define DEFAULT_RETRY           5
120 #define DEFAULT_TIMEOUT         15
121 #define RECHECK                 1               /* Recheck every second to see we we're at the top yet */
122 #define MAX_PERIODIC_ANNOUNCEMENTS 10 /* The maximum periodic announcements we can have */
123 #define DEFAULT_MIN_ANNOUNCE_FREQUENCY 15 /* The minimum number of seconds between position announcements
124                                              The default value of 15 provides backwards compatibility */
125 #define MAX_QUEUE_BUCKETS 53
126
127 #define RES_OKAY        0               /* Action completed */
128 #define RES_EXISTS      (-1)            /* Entry already exists */
129 #define RES_OUTOFMEMORY (-2)            /* Out of memory */
130 #define RES_NOSUCHQUEUE (-3)            /* No such queue */
131 #define RES_NOT_DYNAMIC (-4)            /* Member is not dynamic */
132
133 static char *app = "Queue";
134
135 static char *synopsis = "Queue a call for a call queue";
136
137 static char *descrip =
138 "  Queue(queuename[,options[,URL][,announceoverride][,timeout][,AGI][,macro][,gosub][,rule]):\n"
139 "Queues an incoming call in a particular call queue as defined in queues.conf.\n"
140 "This application will return to the dialplan if the queue does not exist, or\n"
141 "any of the join options cause the caller to not enter the queue.\n"
142 "The option string may contain zero or more of the following characters:\n"
143 "      'c' -- continue in the dialplan if the callee hangs up.\n"
144 "      'd' -- data-quality (modem) call (minimum delay).\n"
145 "      'h' -- allow callee to hang up by pressing *.\n"
146 "      'H' -- allow caller to hang up by pressing *.\n"
147 "      'n' -- no retries on the timeout; will exit this application and \n"
148 "             go to the next step.\n"
149 "      'i' -- ignore call forward requests from queue members and do nothing\n"
150 "             when they are requested.\n"
151 "      'r' -- ring instead of playing MOH. Periodic Announcements are still made, if applicable.\n"
152 "      't' -- allow the called user to transfer the calling user.\n"
153 "      'T' -- allow the calling user to transfer the call.\n"
154 "      'w' -- allow the called user to write the conversation to disk via Monitor.\n"
155 "      'W' -- allow the calling user to write the conversation to disk via Monitor.\n"
156 "      'k' -- Allow the called party to enable parking of the call by sending\n"
157 "             the DTMF sequence defined for call parking in features.conf.\n"
158 "      'K' -- Allow the calling party to enable parking of the call by sending\n"
159 "             the DTMF sequence defined for call parking in features.conf.\n"
160 "      'x' -- allow the called user to write the conversation to disk via MixMonitor\n"
161 "      'X' -- allow the calling user to write the conversation to disk via MixMonitor\n"
162  
163 "  In addition to transferring the call, a call may be parked and then picked\n"
164 "up by another user.\n"
165 "  The optional URL will be sent to the called party if the channel supports\n"
166 "it.\n"
167 "  The optional AGI parameter will setup an AGI script to be executed on the \n"
168 "calling party's channel once they are connected to a queue member.\n"
169 "  The optional macro parameter will run a macro on the \n"
170 "calling party's channel once they are connected to a queue member.\n"
171 "  The optional gosub parameter will run a gosub on the \n"
172 "calling party's channel once they are connected to a queue member.\n"
173 "  The optional rule parameter will cause the queue's defaultrule to be\n"
174 "overridden by the rule specified.\n"
175 "  The timeout will cause the queue to fail out after a specified number of\n"
176 "seconds, checked between each queues.conf 'timeout' and 'retry' cycle.\n"
177 "  This application sets the following channel variable upon completion:\n"
178 "      QUEUESTATUS    The status of the call as a text string, one of\n"
179 "             TIMEOUT | FULL | JOINEMPTY | LEAVEEMPTY | JOINUNAVAIL | LEAVEUNAVAIL | CONTINUE\n";
180
181 static char *app_aqm = "AddQueueMember" ;
182 static char *app_aqm_synopsis = "Dynamically adds queue members" ;
183 static char *app_aqm_descrip =
184 "   AddQueueMember(queuename[,interface[,penalty[,options[,membername]]]]):\n"
185 "Dynamically adds interface to an existing queue.\n"
186 "If the interface is already in the queue it will return an error.\n"
187 "  This application sets the following channel variable upon completion:\n"
188 "     AQMSTATUS    The status of the attempt to add a queue member as a \n"
189 "                     text string, one of\n"
190 "           ADDED | MEMBERALREADY | NOSUCHQUEUE \n"
191 "Example: AddQueueMember(techsupport,SIP/3000)\n"
192 "";
193
194 static char *app_rqm = "RemoveQueueMember" ;
195 static char *app_rqm_synopsis = "Dynamically removes queue members" ;
196 static char *app_rqm_descrip =
197 "   RemoveQueueMember(queuename[,interface[,options]]):\n"
198 "Dynamically removes interface to an existing queue\n"
199 "If the interface is NOT in the queue it will return an error.\n"
200 "  This application sets the following channel variable upon completion:\n"
201 "     RQMSTATUS      The status of the attempt to remove a queue member as a\n"
202 "                     text string, one of\n"
203 "           REMOVED | NOTINQUEUE | NOSUCHQUEUE \n"
204 "Example: RemoveQueueMember(techsupport,SIP/3000)\n"
205 "";
206
207 static char *app_pqm = "PauseQueueMember" ;
208 static char *app_pqm_synopsis = "Pauses a queue member" ;
209 static char *app_pqm_descrip =
210 "   PauseQueueMember([queuename],interface[,options[,reason]]):\n"
211 "Pauses (blocks calls for) a queue member.\n"
212 "The given interface will be paused in the given queue.  This prevents\n"
213 "any calls from being sent from the queue to the interface until it is\n"
214 "unpaused with UnpauseQueueMember or the manager interface.  If no\n"
215 "queuename is given, the interface is paused in every queue it is a\n"
216 "member of. The application will fail if the interface is not found.\n"
217 "The reason string is entirely optional and is used to add extra information\n"
218 "to the appropriate queue_log entries and manager events.\n"
219 "  This application sets the following channel variable upon completion:\n"
220 "     PQMSTATUS      The status of the attempt to pause a queue member as a\n"
221 "                     text string, one of\n"
222 "           PAUSED | NOTFOUND\n"
223 "Example: PauseQueueMember(,SIP/3000)\n";
224
225 static char *app_upqm = "UnpauseQueueMember" ;
226 static char *app_upqm_synopsis = "Unpauses a queue member" ;
227 static char *app_upqm_descrip =
228 "   UnpauseQueueMember([queuename],interface[,options[,reason]]):\n"
229 "Unpauses (resumes calls to) a queue member.\n"
230 "This is the counterpart to PauseQueueMember and operates exactly the\n"
231 "same way, except it unpauses instead of pausing the given interface.\n"
232 "The reason string is entirely optional and is used to add extra information\n"
233 "to the appropriate queue_log entries and manager events.\n"
234 "  This application sets the following channel variable upon completion:\n"
235 "     UPQMSTATUS       The status of the attempt to unpause a queue \n"
236 "                      member as a text string, one of\n"
237 "            UNPAUSED | NOTFOUND\n"
238 "Example: UnpauseQueueMember(,SIP/3000)\n";
239
240 static char *app_ql = "QueueLog" ;
241 static char *app_ql_synopsis = "Writes to the queue_log" ;
242 static char *app_ql_descrip =
243 "   QueueLog(queuename,uniqueid,agent,event[,additionalinfo]):\n"
244 "Allows you to write your own events into the queue log\n"
245 "Example: QueueLog(101,${UNIQUEID},${AGENT},WENTONBREAK,600)\n";
246
247 /*! \brief Persistent Members astdb family */
248 static const char *pm_family = "Queue/PersistentMembers";
249 /* The maximum length of each persistent member queue database entry */
250 #define PM_MAX_LEN 8192
251
252 /*! \brief queues.conf [general] option */
253 static int queue_keep_stats = 0;
254
255 /*! \brief queues.conf [general] option */
256 static int queue_persistent_members = 0;
257
258 /*! \brief queues.conf per-queue weight option */
259 static int use_weight = 0;
260
261 /*! \brief queues.conf [general] option */
262 static int autofill_default = 0;
263
264 /*! \brief queues.conf [general] option */
265 static int montype_default = 0;
266
267 /*! \brief queues.conf [general] option */
268 static int shared_lastcall = 0;
269
270 /*! \brief Subscription to device state change events */
271 static struct ast_event_sub *device_state_sub;
272
273 /*! \brief queues.conf [general] option */
274 static int update_cdr = 0;
275
276 enum queue_result {
277         QUEUE_UNKNOWN = 0,
278         QUEUE_TIMEOUT = 1,
279         QUEUE_JOINEMPTY = 2,
280         QUEUE_LEAVEEMPTY = 3,
281         QUEUE_JOINUNAVAIL = 4,
282         QUEUE_LEAVEUNAVAIL = 5,
283         QUEUE_FULL = 6,
284         QUEUE_CONTINUE = 7,
285 };
286
287 const struct {
288         enum queue_result id;
289         char *text;
290 } queue_results[] = {
291         { QUEUE_UNKNOWN, "UNKNOWN" },
292         { QUEUE_TIMEOUT, "TIMEOUT" },
293         { QUEUE_JOINEMPTY,"JOINEMPTY" },
294         { QUEUE_LEAVEEMPTY, "LEAVEEMPTY" },
295         { QUEUE_JOINUNAVAIL, "JOINUNAVAIL" },
296         { QUEUE_LEAVEUNAVAIL, "LEAVEUNAVAIL" },
297         { QUEUE_FULL, "FULL" },
298         { QUEUE_CONTINUE, "CONTINUE" },
299 };
300
301 /*! \brief We define a custom "local user" structure because we
302    use it not only for keeping track of what is in use but
303    also for keeping track of who we're dialing.
304
305    There are two "links" defined in this structure, q_next and call_next.
306    q_next links ALL defined callattempt structures into a linked list. call_next is
307    a link which allows for a subset of the callattempts to be traversed. This subset
308    is used in wait_for_answer so that irrelevant callattempts are not traversed. This
309    also is helpful so that queue logs are always accurate in the case where a call to 
310    a member times out, especially if using the ringall strategy. */
311
312 struct callattempt {
313         struct callattempt *q_next;
314         struct callattempt *call_next;
315         struct ast_channel *chan;
316         char interface[256];
317         int stillgoing;
318         int metric;
319         int oldstatus;
320         time_t lastcall;
321         struct call_queue *lastqueue;
322         struct member *member;
323 };
324
325
326 struct queue_ent {
327         struct call_queue *parent;             /*!< What queue is our parent */
328         char moh[80];                          /*!< Name of musiconhold to be used */
329         char announce[80];                     /*!< Announcement to play for member when call is answered */
330         char context[AST_MAX_CONTEXT];         /*!< Context when user exits queue */
331         char digits[AST_MAX_EXTENSION];        /*!< Digits entered while in queue */
332         int valid_digits;                              /*!< Digits entered correspond to valid extension. Exited */
333         int pos;                               /*!< Where we are in the queue */
334         int prio;                              /*!< Our priority */
335         int last_pos_said;                     /*!< Last position we told the user */
336         time_t last_periodic_announce_time;    /*!< The last time we played a periodic announcement */
337         int last_periodic_announce_sound;      /*!< The last periodic announcement we made */
338         time_t last_pos;                       /*!< Last time we told the user their position */
339         int opos;                              /*!< Where we started in the queue */
340         int handled;                           /*!< Whether our call was handled */
341         int pending;                           /*!< Non-zero if we are attempting to call a member */
342         int max_penalty;                       /*!< Limit the members that can take this call to this penalty or lower */
343         int min_penalty;                       /*!< Limit the members that can take this call to this penalty or higher */
344         int linpos;                                                        /*!< If using linear strategy, what position are we at? */
345         int linwrapped;                                            /*!< Is the linpos wrapped? */
346         time_t start;                          /*!< When we started holding */
347         time_t expire;                         /*!< When this entry should expire (time out of queue) */
348         struct ast_channel *chan;              /*!< Our channel */
349         AST_LIST_HEAD_NOLOCK(,penalty_rule) qe_rules; /*!< Local copy of the queue's penalty rules */
350         struct penalty_rule *pr;               /*!< Pointer to the next penalty rule to implement */
351         struct queue_ent *next;                /*!< The next queue entry */
352 };
353
354 struct member {
355         char interface[80];                 /*!< Technology/Location */
356         char membername[80];                /*!< Member name to use in queue logs */
357         int penalty;                        /*!< Are we a last resort? */
358         int calls;                          /*!< Number of calls serviced by this member */
359         int dynamic;                        /*!< Are we dynamically added? */
360         int realtime;                       /*!< Is this member realtime? */
361         int status;                         /*!< Status of queue member */
362         int paused;                         /*!< Are we paused (not accepting calls)? */
363         time_t lastcall;                    /*!< When last successful call was hungup */
364         struct call_queue *lastqueue;       /*!< Last queue we received a call */
365         unsigned int dead:1;                /*!< Used to detect members deleted in realtime */
366         unsigned int delme:1;               /*!< Flag to delete entry on reload */
367 };
368
369 struct member_interface {
370         char interface[80];
371         AST_LIST_ENTRY(member_interface) list;    /*!< Next call queue */
372 };
373
374 static AST_LIST_HEAD_STATIC(interfaces, member_interface);
375
376 /* values used in multi-bit flags in call_queue */
377 #define QUEUE_EMPTY_NORMAL 1
378 #define QUEUE_EMPTY_STRICT 2
379 #define QUEUE_EMPTY_LOOSE 3
380 #define ANNOUNCEHOLDTIME_ALWAYS 1
381 #define ANNOUNCEHOLDTIME_ONCE 2
382 #define QUEUE_EVENT_VARIABLES 3
383
384 struct penalty_rule {
385         int time;                           /*!< Number of seconds that need to pass before applying this rule */
386         int max_value;                      /*!< The amount specified in the penalty rule for max penalty */
387         int min_value;                      /*!< The amount specified in the penalty rule for min penalty */
388         int max_relative;                   /*!< Is the max adjustment relative? 1 for relative, 0 for absolute */
389         int min_relative;                   /*!< Is the min adjustment relative? 1 for relative, 0 for absolute */
390         AST_LIST_ENTRY(penalty_rule) list;  /*!< Next penalty_rule */
391 };
392
393 struct call_queue {
394         AST_DECLARE_STRING_FIELDS(
395                 /*! Queue name */
396                 AST_STRING_FIELD(name);
397                 /*! Music on Hold class */
398                 AST_STRING_FIELD(moh);
399                 /*! Announcement to play when call is answered */
400                 AST_STRING_FIELD(announce);
401                 /*! Exit context */
402                 AST_STRING_FIELD(context);
403                 /*! Macro to run upon member connection */
404                 AST_STRING_FIELD(membermacro);
405                 /*! Gosub to run upon member connection */
406                 AST_STRING_FIELD(membergosub);
407                 /*! Default rule to use if none specified in call to Queue() */
408                 AST_STRING_FIELD(defaultrule);
409                 /*! Sound file: "Your call is now first in line" (def. queue-youarenext) */
410                 AST_STRING_FIELD(sound_next);
411                 /*! Sound file: "There are currently" (def. queue-thereare) */
412                 AST_STRING_FIELD(sound_thereare);
413                 /*! Sound file: "calls waiting to speak to a representative." (def. queue-callswaiting) */
414                 AST_STRING_FIELD(sound_calls);
415                 /*! Sound file: "The current estimated total holdtime is" (def. queue-holdtime) */
416                 AST_STRING_FIELD(sound_holdtime);
417                 /*! Sound file: "minutes." (def. queue-minutes) */
418                 AST_STRING_FIELD(sound_minutes);
419                 /*! Sound file: "less-than" (def. queue-lessthan) */
420                 AST_STRING_FIELD(sound_lessthan);
421                 /*! Sound file: "seconds." (def. queue-seconds) */
422                 AST_STRING_FIELD(sound_seconds);
423                 /*! Sound file: "Thank you for your patience." (def. queue-thankyou) */
424                 AST_STRING_FIELD(sound_thanks);
425                 /*! Sound file: Custom announce for caller, no default */
426                 AST_STRING_FIELD(sound_callerannounce);
427                 /*! Sound file: "Hold time" (def. queue-reporthold) */
428                 AST_STRING_FIELD(sound_reporthold);
429         );
430         /*! Sound files: Custom announce, no default */
431         struct ast_str *sound_periodicannounce[MAX_PERIODIC_ANNOUNCEMENTS];
432         unsigned int dead:1;
433         unsigned int joinempty:2;
434         unsigned int eventwhencalled:2;
435         unsigned int leavewhenempty:2;
436         unsigned int ringinuse:1;
437         unsigned int setinterfacevar:1;
438         unsigned int setqueuevar:1;
439         unsigned int setqueueentryvar:1;
440         unsigned int reportholdtime:1;
441         unsigned int wrapped:1;
442         unsigned int timeoutrestart:1;
443         unsigned int announceholdtime:2;
444         unsigned int announceposition:1;
445         int strategy:4;
446         unsigned int maskmemberstatus:1;
447         unsigned int realtime:1;
448         unsigned int found:1;
449         int announcefrequency;              /*!< How often to announce their position */
450         int minannouncefrequency;           /*!< The minimum number of seconds between position announcements (def. 15) */
451         int periodicannouncefrequency;      /*!< How often to play periodic announcement */
452         int roundingseconds;                /*!< How many seconds do we round to? */
453         int holdtime;                       /*!< Current avg holdtime, based on recursive boxcar filter */
454         int callscompleted;                 /*!< Number of queue calls completed */
455         int callsabandoned;                 /*!< Number of queue calls abandoned */
456         int servicelevel;                   /*!< seconds setting for servicelevel*/
457         int callscompletedinsl;             /*!< Number of calls answered with servicelevel*/
458         char monfmt[8];                     /*!< Format to use when recording calls */
459         int montype;                        /*!< Monitor type  Monitor vs. MixMonitor */
460         int count;                          /*!< How many entries */
461         int maxlen;                         /*!< Max number of entries */
462         int wrapuptime;                     /*!< Wrapup Time */
463
464         int retry;                          /*!< Retry calling everyone after this amount of time */
465         int timeout;                        /*!< How long to wait for an answer */
466         int weight;                         /*!< Respective weight */
467         int autopause;                      /*!< Auto pause queue members if they fail to answer */
468
469         /* Queue strategy things */
470         int rrpos;                          /*!< Round Robin - position */
471         int memberdelay;                    /*!< Seconds to delay connecting member to caller */
472         int autofill;                       /*!< Ignore the head call status and ring an available agent */
473         
474         struct ao2_container *members;             /*!< Head of the list of members */
475         /*! 
476          * \brief Number of members _logged in_
477          * \note There will be members in the members container that are not logged
478          *       in, so this can not simply be replaced with ao2_container_count(). 
479          */
480         int membercount;
481         struct queue_ent *head;             /*!< Head of the list of callers */
482         AST_LIST_ENTRY(call_queue) list;    /*!< Next call queue */
483         AST_LIST_HEAD_NOLOCK(, penalty_rule) rules; /*!< The list of penalty rules to invoke */
484 };
485
486 struct rule_list {
487         char name[80];
488         AST_LIST_HEAD_NOLOCK(,penalty_rule) rules;
489         AST_LIST_ENTRY(rule_list) list;
490 };
491
492 AST_LIST_HEAD_STATIC(rule_lists, rule_list);
493
494 static struct ao2_container *queues;
495
496 static void update_realtime_members(struct call_queue *q);
497 static int set_member_paused(const char *queuename, const char *interface, const char *reason, int paused);
498
499 static void set_queue_result(struct ast_channel *chan, enum queue_result res)
500 {
501         int i;
502
503         for (i = 0; i < sizeof(queue_results) / sizeof(queue_results[0]); i++) {
504                 if (queue_results[i].id == res) {
505                         pbx_builtin_setvar_helper(chan, "QUEUESTATUS", queue_results[i].text);
506                         return;
507                 }
508         }
509 }
510
511 static char *int2strat(int strategy)
512 {
513         int x;
514
515         for (x = 0; x < sizeof(strategies) / sizeof(strategies[0]); x++) {
516                 if (strategy == strategies[x].strategy)
517                         return strategies[x].name;
518         }
519
520         return "<unknown>";
521 }
522
523 static int strat2int(const char *strategy)
524 {
525         int x;
526
527         for (x = 0; x < sizeof(strategies) / sizeof(strategies[0]); x++) {
528                 if (!strcasecmp(strategy, strategies[x].name))
529                         return strategies[x].strategy;
530         }
531
532         return -1;
533 }
534
535 static int queue_hash_cb(const void *obj, const int flags)
536 {
537         const struct call_queue *q = obj;
538         return ast_str_hash(q->name);
539 }
540
541 static int queue_cmp_cb(void *obj, void *arg, int flags)
542 {
543         struct call_queue *q = obj, *q2 = arg;
544         return !strcasecmp(q->name, q2->name) ? CMP_MATCH : 0;
545 }
546
547 static inline struct call_queue *queue_ref(struct call_queue *q)
548 {
549         ao2_ref(q, 1);
550         return q;
551 }
552
553 static inline struct call_queue *queue_unref(struct call_queue *q)
554 {
555         ao2_ref(q, -1);
556         return q;
557 }
558
559 static void set_queue_variables(struct queue_ent *qe)
560 {
561
562         char interfacevar[256]="";
563         float sl = 0;
564         
565         if (qe->parent->setqueuevar) {
566         sl = 0;
567         if (qe->parent->callscompleted > 0) 
568                 sl = 100 * ((float) qe->parent->callscompletedinsl / (float) qe->parent->callscompleted);
569
570         snprintf(interfacevar,sizeof(interfacevar),
571                 "QUEUEMAX=%d|QUEUESTRATEGY=%s|QUEUECALLS=%d|QUEUEHOLDTIME=%d|QUEUECOMPLETED=%d|QUEUEABANDONED=%d|QUEUESRVLEVEL=%d|QUEUESRVLEVELPERF=%2.1f",
572                 qe->parent->maxlen, int2strat(qe->parent->strategy), qe->parent->count, qe->parent->holdtime, qe->parent->callscompleted,
573                 qe->parent->callsabandoned,  qe->parent->servicelevel, sl);
574         
575         pbx_builtin_setvar(qe->chan, interfacevar); 
576         }
577 }
578
579 /*! \brief Insert the 'new' entry after the 'prev' entry of queue 'q' */
580 static inline void insert_entry(struct call_queue *q, struct queue_ent *prev, struct queue_ent *new, int *pos)
581 {
582         struct queue_ent *cur;
583
584         if (!q || !new)
585                 return;
586         if (prev) {
587                 cur = prev->next;
588                 prev->next = new;
589         } else {
590                 cur = q->head;
591                 q->head = new;
592         }
593         new->next = cur;
594         new->parent = q;
595         new->pos = ++(*pos);
596         new->opos = *pos;
597 }
598
599 enum queue_member_status {
600         QUEUE_NO_MEMBERS,
601         QUEUE_NO_REACHABLE_MEMBERS,
602         QUEUE_NO_UNPAUSED_REACHABLE_MEMBERS,
603         QUEUE_NORMAL
604 };
605
606 static enum queue_member_status get_member_status(struct call_queue *q, int max_penalty, int min_penalty)
607 {
608         struct member *member;
609         struct ao2_iterator mem_iter;
610         enum queue_member_status result = QUEUE_NO_MEMBERS;
611
612         ao2_lock(q);
613         mem_iter = ao2_iterator_init(q->members, 0);
614         for (; (member = ao2_iterator_next(&mem_iter)); ao2_ref(member, -1)) {
615                 if ((max_penalty && (member->penalty > max_penalty)) || (min_penalty && (member->penalty < min_penalty)))
616                         continue;
617
618                 switch (member->status) {
619                 case AST_DEVICE_INVALID:
620                         /* nothing to do */
621                         break;
622                 case AST_DEVICE_UNAVAILABLE:
623                         if (result != QUEUE_NO_UNPAUSED_REACHABLE_MEMBERS) 
624                                 result = QUEUE_NO_REACHABLE_MEMBERS;
625                         break;
626                 default:
627                         if (member->paused) {
628                                 result = QUEUE_NO_UNPAUSED_REACHABLE_MEMBERS;
629                         } else {
630                                 ao2_unlock(q);
631                                 ao2_ref(member, -1);
632                                 return QUEUE_NORMAL;
633                         }
634                         break;
635                 }
636         }
637
638         ao2_unlock(q);
639         return result;
640 }
641
642 struct statechange {
643         AST_LIST_ENTRY(statechange) entry;
644         int state;
645         char dev[0];
646 };
647
648 static void *handle_statechange(struct statechange *sc)
649 {
650         struct call_queue *q;
651         struct member *cur;
652         struct ao2_iterator mem_iter;
653         struct member_interface *curint;
654         struct ao2_iterator queue_iter;
655         char *loc;
656         char *technology;
657
658         technology = ast_strdupa(sc->dev);
659         loc = strchr(technology, '/');
660         if (loc) {
661                 *loc++ = '\0';
662         } else {
663                 return NULL;
664         }
665
666         AST_LIST_LOCK(&interfaces);
667         AST_LIST_TRAVERSE(&interfaces, curint, list) {
668                 char *interface;
669                 char *slash_pos;
670                 interface = ast_strdupa(curint->interface);
671                 if ((slash_pos = strchr(interface, '/')))
672                         if ((slash_pos = strchr(slash_pos + 1, '/')))
673                                 *slash_pos = '\0';
674
675                 if (!strcasecmp(interface, sc->dev))
676                         break;
677         }
678         AST_LIST_UNLOCK(&interfaces);
679
680         if (!curint) {
681                 ast_debug(3, "Device '%s/%s' changed to state '%d' (%s) but we don't care because they're not a member of any queue.\n", technology, loc, sc->state, devstate2str(sc->state));
682                 return NULL;
683         }
684
685         ast_debug(1, "Device '%s/%s' changed to state '%d' (%s)\n", technology, loc, sc->state, devstate2str(sc->state));
686         queue_iter = ao2_iterator_init(queues, 0);
687         while ((q = ao2_iterator_next(&queue_iter))) {
688                 ao2_lock(q);
689                 mem_iter = ao2_iterator_init(q->members, 0);
690                 while ((cur = ao2_iterator_next(&mem_iter))) {
691                         char *interface;
692                         char *slash_pos;
693                         interface = ast_strdupa(cur->interface);
694                         if ((slash_pos = strchr(interface, '/')))
695                                 if ((slash_pos = strchr(slash_pos + 1, '/')))
696                                         *slash_pos = '\0';
697
698                         if (strcasecmp(sc->dev, interface)) {
699                                 ao2_ref(cur, -1);
700                                 continue;
701                         }
702
703                         if (cur->status != sc->state) {
704                                 cur->status = sc->state;
705                                 if (q->maskmemberstatus) {
706                                         ao2_ref(cur, -1);
707                                         continue;
708                                 }
709
710                                 manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
711                                         "Queue: %s\r\n"
712                                         "Location: %s\r\n"
713                                         "MemberName: %s\r\n"
714                                         "Membership: %s\r\n"
715                                         "Penalty: %d\r\n"
716                                         "CallsTaken: %d\r\n"
717                                         "LastCall: %d\r\n"
718                                         "Status: %d\r\n"
719                                         "Paused: %d\r\n",
720                                         q->name, cur->interface, cur->membername, cur->dynamic ? "dynamic" : cur->realtime ? "realtime" : "static",
721                                         cur->penalty, cur->calls, (int)cur->lastcall, cur->status, cur->paused);
722                         }
723                         ao2_ref(cur, -1);
724                 }
725                 queue_unref(q);
726                 ao2_unlock(q);
727         }
728
729         return NULL;
730 }
731
732 /*!
733  * \brief Data used by the device state thread
734  */
735 static struct {
736         /*! Set to 1 to stop the thread */
737         unsigned int stop:1;
738         /*! The device state monitoring thread */
739         pthread_t thread;
740         /*! Lock for the state change queue */
741         ast_mutex_t lock;
742         /*! Condition for the state change queue */
743         ast_cond_t cond;
744         /*! Queue of state changes */
745         AST_LIST_HEAD_NOLOCK(, statechange) state_change_q;
746 } device_state = {
747         .thread = AST_PTHREADT_NULL,
748 };
749
750 static void *device_state_thread(void *data)
751 {
752         struct statechange *sc = NULL;
753
754         while (!device_state.stop) {
755                 ast_mutex_lock(&device_state.lock);
756                 if (!(sc = AST_LIST_REMOVE_HEAD(&device_state.state_change_q, entry))) {
757                         ast_cond_wait(&device_state.cond, &device_state.lock);
758                         sc = AST_LIST_REMOVE_HEAD(&device_state.state_change_q, entry);
759                 }
760                 ast_mutex_unlock(&device_state.lock);
761
762                 /* Check to see if we were woken up to see the request to stop */
763                 if (device_state.stop)
764                         break;
765
766                 if (!sc)
767                         continue;
768
769                 handle_statechange(sc);
770
771                 ast_free(sc);
772                 sc = NULL;
773         }
774
775         if (sc)
776                 ast_free(sc);
777
778         while ((sc = AST_LIST_REMOVE_HEAD(&device_state.state_change_q, entry)))
779                 ast_free(sc);
780
781         return NULL;
782 }
783
784 static int statechange_queue(const char *dev, enum ast_device_state state)
785 {
786         struct statechange *sc;
787
788         if (!(sc = ast_calloc(1, sizeof(*sc) + strlen(dev) + 1)))
789                 return 0;
790
791         sc->state = state;
792         strcpy(sc->dev, dev);
793
794         ast_mutex_lock(&device_state.lock);
795         AST_LIST_INSERT_TAIL(&device_state.state_change_q, sc, entry);
796         ast_cond_signal(&device_state.cond);
797         ast_mutex_unlock(&device_state.lock);
798
799         return 0;
800 }
801
802 static void device_state_cb(const struct ast_event *event, void *unused)
803 {
804         enum ast_device_state state;
805         const char *device;
806
807         state = ast_event_get_ie_uint(event, AST_EVENT_IE_STATE);
808         device = ast_event_get_ie_str(event, AST_EVENT_IE_DEVICE);
809
810         if (ast_strlen_zero(device)) {
811                 ast_log(LOG_ERROR, "Received invalid event that had no device IE\n");
812                 return;
813         }
814
815         statechange_queue(device, state);
816 }
817
818 static struct member *create_queue_member(const char *interface, const char *membername, int penalty, int paused)
819 {
820         struct member *cur;
821         
822         if ((cur = ao2_alloc(sizeof(*cur), NULL))) {
823                 cur->penalty = penalty;
824                 cur->paused = paused;
825                 ast_copy_string(cur->interface, interface, sizeof(cur->interface));
826                 if (!ast_strlen_zero(membername))
827                         ast_copy_string(cur->membername, membername, sizeof(cur->membername));
828                 else
829                         ast_copy_string(cur->membername, interface, sizeof(cur->membername));
830                 if (!strchr(cur->interface, '/'))
831                         ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
832                 cur->status = ast_device_state(interface);
833         }
834
835         return cur;
836 }
837
838
839 static int compress_char(const char c)
840 {
841         if (c < 32)
842                 return 0;
843         else if (c > 96)
844                 return c - 64;
845         else
846                 return c - 32;
847 }
848
849 static int member_hash_fn(const void *obj, const int flags)
850 {
851         const struct member *mem = obj;
852         const char *chname = strchr(mem->interface, '/');
853         int ret = 0, i;
854         if (!chname)
855                 chname = mem->interface;
856         for (i = 0; i < 5 && chname[i]; i++)
857                 ret += compress_char(chname[i]) << (i * 6);
858         return ret;
859 }
860
861 static int member_cmp_fn(void *obj1, void *obj2, int flags)
862 {
863         struct member *mem1 = obj1, *mem2 = obj2;
864         return strcasecmp(mem1->interface, mem2->interface) ? 0 : CMP_MATCH;
865 }
866
867 static void init_queue(struct call_queue *q)
868 {
869         int i;
870         struct penalty_rule *pr_iter;
871
872         q->dead = 0;
873         q->retry = DEFAULT_RETRY;
874         q->timeout = -1;
875         q->maxlen = 0;
876         q->announcefrequency = 0;
877         q->minannouncefrequency = DEFAULT_MIN_ANNOUNCE_FREQUENCY;
878         q->announceholdtime = 0;
879         q->announceholdtime = 1;
880         q->roundingseconds = 0; /* Default - don't announce seconds */
881         q->servicelevel = 0;
882         q->ringinuse = 1;
883         q->setinterfacevar = 0;
884         q->setqueuevar = 0;
885         q->setqueueentryvar = 0;
886         q->autofill = autofill_default;
887         q->montype = montype_default;
888         q->monfmt[0] = '\0';
889         q->periodicannouncefrequency = 0;
890         if (!q->members) {
891                 if (q->strategy == QUEUE_STRATEGY_LINEAR)
892                         /* linear strategy depends on order, so we have to place all members in a single bucket */
893                         q->members = ao2_container_alloc(1, member_hash_fn, member_cmp_fn);
894                 else
895                         q->members = ao2_container_alloc(37, member_hash_fn, member_cmp_fn);
896         }
897         q->membercount = 0;
898         q->found = 1;
899
900         ast_string_field_set(q, sound_next, "queue-youarenext");
901         ast_string_field_set(q, sound_thereare, "queue-thereare");
902         ast_string_field_set(q, sound_calls, "queue-callswaiting");
903         ast_string_field_set(q, sound_holdtime, "queue-holdtime");
904         ast_string_field_set(q, sound_minutes, "queue-minutes");
905         ast_string_field_set(q, sound_seconds, "queue-seconds");
906         ast_string_field_set(q, sound_thanks, "queue-thankyou");
907         ast_string_field_set(q, sound_lessthan, "queue-less-than");
908         ast_string_field_set(q, sound_reporthold, "queue-reporthold");
909
910         if ((q->sound_periodicannounce[0] = ast_str_create(32)))
911                 ast_str_set(&q->sound_periodicannounce[0], 0, "queue-periodic-announce");
912
913         for (i = 1; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
914                 if (q->sound_periodicannounce[i])
915                         ast_str_set(&q->sound_periodicannounce[i], 0, "%s", "");
916         }
917
918         while ((pr_iter = AST_LIST_REMOVE_HEAD(&q->rules,list)))
919                 ast_free(pr_iter);
920 }
921
922 static void clear_queue(struct call_queue *q)
923 {
924         q->holdtime = 0;
925         q->callscompleted = 0;
926         q->callsabandoned = 0;
927         q->callscompletedinsl = 0;
928         q->wrapuptime = 0;
929 }
930
931 static int add_to_interfaces(const char *interface)
932 {
933         struct member_interface *curint;
934
935         AST_LIST_LOCK(&interfaces);
936         AST_LIST_TRAVERSE(&interfaces, curint, list) {
937                 if (!strcasecmp(curint->interface, interface))
938                         break;
939         }
940
941         if (curint) {
942                 AST_LIST_UNLOCK(&interfaces);
943                 return 0;
944         }
945
946         ast_debug(1, "Adding %s to the list of interfaces that make up all of our queue members.\n", interface);
947         
948         if ((curint = ast_calloc(1, sizeof(*curint)))) {
949                 ast_copy_string(curint->interface, interface, sizeof(curint->interface));
950                 AST_LIST_INSERT_HEAD(&interfaces, curint, list);
951         }
952         AST_LIST_UNLOCK(&interfaces);
953
954         return 0;
955 }
956
957 static int interface_exists_global(const char *interface)
958 {
959         struct call_queue *q;
960         struct member *mem, tmpmem;
961         struct ao2_iterator queue_iter;
962         int ret = 0;
963
964         ast_copy_string(tmpmem.interface, interface, sizeof(tmpmem.interface));
965         queue_iter = ao2_iterator_init(queues, 0);
966         while ((q = ao2_iterator_next(&queue_iter))) {
967
968                 ao2_lock(q);
969                 if ((mem = ao2_find(q->members, &tmpmem, OBJ_POINTER))) {
970                         ao2_ref(mem, -1);
971                         ao2_unlock(q);
972                         queue_unref(q);
973                         ret = 1;
974                         break;
975                 }
976                 ao2_unlock(q);
977                 queue_unref(q);
978         }
979
980         return ret;
981 }
982
983 static int remove_from_interfaces(const char *interface)
984 {
985         struct member_interface *curint;
986
987         AST_LIST_LOCK(&interfaces);
988         AST_LIST_TRAVERSE_SAFE_BEGIN(&interfaces, curint, list) {
989                 if (!strcasecmp(curint->interface, interface)) {
990                         if (!interface_exists_global(interface)) {
991                                 ast_debug(1, "Removing %s from the list of interfaces that make up all of our queue members.\n", interface);
992                                 AST_LIST_REMOVE_CURRENT(list);
993                                 ast_free(curint);
994                         }
995                         break;
996                 }
997         }
998         AST_LIST_TRAVERSE_SAFE_END;
999         AST_LIST_UNLOCK(&interfaces);
1000
1001         return 0;
1002 }
1003
1004 static void clear_and_free_interfaces(void)
1005 {
1006         struct member_interface *curint;
1007
1008         AST_LIST_LOCK(&interfaces);
1009         while ((curint = AST_LIST_REMOVE_HEAD(&interfaces, list)))
1010                 ast_free(curint);
1011         AST_LIST_UNLOCK(&interfaces);
1012 }
1013
1014 /*Note: call this with the rule_lists locked */
1015 static int insert_penaltychange (const char *list_name, const char *content, const int linenum)
1016 {
1017         char *timestr, *maxstr, *minstr, *contentdup;
1018         struct penalty_rule *rule = NULL, *rule_iter;
1019         struct rule_list *rl_iter;
1020         int time, inserted = 0;
1021
1022         if (!(rule = ast_calloc(1, sizeof(*rule)))) {
1023                 ast_log(LOG_ERROR, "Cannot allocate memory for penaltychange rule at line %d!\n", linenum);
1024                 return -1;
1025         }
1026
1027         contentdup = ast_strdupa(content);
1028         
1029         if (!(maxstr = strchr(contentdup, ','))) {
1030                 ast_log(LOG_WARNING, "Improperly formatted penaltychange rule at line %d. Ignoring.\n", linenum);
1031                 ast_free(rule);
1032                 return -1;
1033         }
1034
1035         *maxstr++ = '\0';
1036         timestr = contentdup;
1037
1038         if ((time = atoi(timestr)) < 0) {
1039                 ast_log(LOG_WARNING, "Improper time parameter specified for penaltychange rule at line %d. Ignoring.\n", linenum);
1040                 ast_free(rule);
1041                 return -1;
1042         }
1043
1044         rule->time = time;
1045
1046         if ((minstr = strchr(maxstr,',')))
1047                 *minstr++ = '\0';
1048         
1049         /* The last check will evaluate true if either no penalty change is indicated for a given rule
1050          * OR if a min penalty change is indicated but no max penalty change is */
1051         if (*maxstr == '+' || *maxstr == '-' || *maxstr == '\0') {
1052                 rule->max_relative = 1;
1053         }
1054
1055         rule->max_value = atoi(maxstr);
1056
1057         if (!ast_strlen_zero(minstr)) {
1058                 if (*minstr == '+' || *minstr == '-')
1059                         rule->min_relative = 1;
1060                 rule->min_value = atoi(minstr);
1061         } else /*there was no minimum specified, so assume this means no change*/
1062                 rule->min_relative = 1;
1063
1064         /*We have the rule made, now we need to insert it where it belongs*/
1065         AST_LIST_TRAVERSE(&rule_lists, rl_iter, list){
1066                 if (strcasecmp(rl_iter->name, list_name))
1067                         continue;
1068
1069                 AST_LIST_TRAVERSE_SAFE_BEGIN(&rl_iter->rules, rule_iter, list) {
1070                         if (rule->time < rule_iter->time) {
1071                                 AST_LIST_INSERT_BEFORE_CURRENT(rule, list);
1072                                 inserted = 1;
1073                                 break;
1074                         }
1075                 }
1076                 AST_LIST_TRAVERSE_SAFE_END;
1077         
1078                 if (!inserted) {
1079                         AST_LIST_INSERT_TAIL(&rl_iter->rules, rule, list);
1080                 }
1081         }
1082
1083         return 0;
1084 }
1085
1086 /*! \brief Configure a queue parameter.
1087 \par
1088    For error reporting, line number is passed for .conf static configuration.
1089    For Realtime queues, linenum is -1.
1090    The failunknown flag is set for config files (and static realtime) to show
1091    errors for unknown parameters. It is cleared for dynamic realtime to allow
1092    extra fields in the tables. */
1093 static void queue_set_param(struct call_queue *q, const char *param, const char *val, int linenum, int failunknown)
1094 {
1095         if (!strcasecmp(param, "musicclass") || 
1096                 !strcasecmp(param, "music") || !strcasecmp(param, "musiconhold")) {
1097                 ast_string_field_set(q, moh, val);
1098         } else if (!strcasecmp(param, "announce")) {
1099                 ast_string_field_set(q, announce, val);
1100         } else if (!strcasecmp(param, "context")) {
1101                 ast_string_field_set(q, context, val);
1102         } else if (!strcasecmp(param, "timeout")) {
1103                 q->timeout = atoi(val);
1104                 if (q->timeout < 0)
1105                         q->timeout = DEFAULT_TIMEOUT;
1106         } else if (!strcasecmp(param, "ringinuse")) {
1107                 q->ringinuse = ast_true(val);
1108         } else if (!strcasecmp(param, "setinterfacevar")) {
1109                 q->setinterfacevar = ast_true(val);
1110         } else if (!strcasecmp(param, "setqueuevar")) {
1111                 q->setqueuevar = ast_true(val);
1112         } else if (!strcasecmp(param, "setqueueentryvar")) {
1113                 q->setqueueentryvar = ast_true(val);
1114         } else if (!strcasecmp(param, "monitor-format")) {
1115                 ast_copy_string(q->monfmt, val, sizeof(q->monfmt));
1116         } else if (!strcasecmp(param, "membermacro")) {
1117                 ast_string_field_set(q, membermacro, val);
1118         } else if (!strcasecmp(param, "membergosub")) {
1119                 ast_string_field_set(q, membergosub, val);
1120         } else if (!strcasecmp(param, "queue-youarenext")) {
1121                 ast_string_field_set(q, sound_next, val);
1122         } else if (!strcasecmp(param, "queue-thereare")) {
1123                 ast_string_field_set(q, sound_thereare, val);
1124         } else if (!strcasecmp(param, "queue-callswaiting")) {
1125                 ast_string_field_set(q, sound_calls, val);
1126         } else if (!strcasecmp(param, "queue-holdtime")) {
1127                 ast_string_field_set(q, sound_holdtime, val);
1128         } else if (!strcasecmp(param, "queue-minutes")) {
1129                 ast_string_field_set(q, sound_minutes, val);
1130         } else if (!strcasecmp(param, "queue-seconds")) {
1131                 ast_string_field_set(q, sound_seconds, val);
1132         } else if (!strcasecmp(param, "queue-lessthan")) {
1133                 ast_string_field_set(q, sound_lessthan, val);
1134         } else if (!strcasecmp(param, "queue-thankyou")) {
1135                 ast_string_field_set(q, sound_thanks, val);
1136         } else if (!strcasecmp(param, "queue-callerannounce")) {
1137                 ast_string_field_set(q, sound_callerannounce, val);
1138         } else if (!strcasecmp(param, "queue-reporthold")) {
1139                 ast_string_field_set(q, sound_reporthold, val);
1140         } else if (!strcasecmp(param, "announce-frequency")) {
1141                 q->announcefrequency = atoi(val);
1142         } else if (!strcasecmp(param, "min-announce-frequency")) {
1143                 q->minannouncefrequency = atoi(val);
1144                 ast_debug(1, "%s=%s for queue '%s'\n", param, val, q->name);
1145         } else if (!strcasecmp(param, "announce-round-seconds")) {
1146                 q->roundingseconds = atoi(val);
1147                 /* Rounding to any other values just doesn't make sense... */
1148                 if (!(q->roundingseconds == 0 || q->roundingseconds == 1 || q->roundingseconds == 5 || q->roundingseconds == 10
1149                         || q->roundingseconds == 15 || q->roundingseconds == 20 || q->roundingseconds == 30)) {
1150                         if (linenum >= 0) {
1151                                 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
1152                                         "using 0 instead for queue '%s' at line %d of queues.conf\n",
1153                                         val, param, q->name, linenum);
1154                         } else {
1155                                 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
1156                                         "using 0 instead for queue '%s'\n", val, param, q->name);
1157                         }
1158                         q->roundingseconds=0;
1159                 }
1160         } else if (!strcasecmp(param, "announce-holdtime")) {
1161                 if (!strcasecmp(val, "once"))
1162                         q->announceholdtime = ANNOUNCEHOLDTIME_ONCE;
1163                 else if (ast_true(val))
1164                         q->announceholdtime = ANNOUNCEHOLDTIME_ALWAYS;
1165                 else
1166                         q->announceholdtime = 0;
1167         } else if (!strcasecmp(param, "announce-position")) {
1168                 q->announceposition = ast_true(val);
1169         } else if (!strcasecmp(param, "periodic-announce")) {
1170                 if (strchr(val, ',')) {
1171                         char *s, *buf = ast_strdupa(val);
1172                         unsigned int i = 0;
1173
1174                         while ((s = strsep(&buf, ",|"))) {
1175                                 if (!q->sound_periodicannounce[i])
1176                                         q->sound_periodicannounce[i] = ast_str_create(16);
1177                                 ast_str_set(&q->sound_periodicannounce[i], 0, s);
1178                                 i++;
1179                                 if (i == MAX_PERIODIC_ANNOUNCEMENTS)
1180                                         break;
1181                         }
1182                 } else {
1183                         ast_str_set(&q->sound_periodicannounce[0], 0, val);
1184                 }
1185         } else if (!strcasecmp(param, "periodic-announce-frequency")) {
1186                 q->periodicannouncefrequency = atoi(val);
1187         } else if (!strcasecmp(param, "retry")) {
1188                 q->retry = atoi(val);
1189                 if (q->retry <= 0)
1190                         q->retry = DEFAULT_RETRY;
1191         } else if (!strcasecmp(param, "wrapuptime")) {
1192                 q->wrapuptime = atoi(val);
1193         } else if (!strcasecmp(param, "autofill")) {
1194                 q->autofill = ast_true(val);
1195         } else if (!strcasecmp(param, "monitor-type")) {
1196                 if (!strcasecmp(val, "mixmonitor"))
1197                         q->montype = 1;
1198         } else if (!strcasecmp(param, "autopause")) {
1199                 q->autopause = ast_true(val);
1200         } else if (!strcasecmp(param, "maxlen")) {
1201                 q->maxlen = atoi(val);
1202                 if (q->maxlen < 0)
1203                         q->maxlen = 0;
1204         } else if (!strcasecmp(param, "servicelevel")) {
1205                 q->servicelevel= atoi(val);
1206         } else if (!strcasecmp(param, "strategy")) {
1207                 /* We already have set this, no need to do it again */
1208                 return;
1209         } else if (!strcasecmp(param, "joinempty")) {
1210                 if (!strcasecmp(val, "loose"))
1211                         q->joinempty = QUEUE_EMPTY_LOOSE;
1212                 else if (!strcasecmp(val, "strict"))
1213                         q->joinempty = QUEUE_EMPTY_STRICT;
1214                 else if (ast_true(val))
1215                         q->joinempty = QUEUE_EMPTY_NORMAL;
1216                 else
1217                         q->joinempty = 0;
1218         } else if (!strcasecmp(param, "leavewhenempty")) {
1219                 if (!strcasecmp(val, "loose"))
1220                         q->leavewhenempty = QUEUE_EMPTY_LOOSE;
1221                 else if (!strcasecmp(val, "strict"))
1222                         q->leavewhenempty = QUEUE_EMPTY_STRICT;
1223                 else if (ast_true(val))
1224                         q->leavewhenempty = QUEUE_EMPTY_NORMAL;
1225                 else
1226                         q->leavewhenempty = 0;
1227         } else if (!strcasecmp(param, "eventmemberstatus")) {
1228                 q->maskmemberstatus = !ast_true(val);
1229         } else if (!strcasecmp(param, "eventwhencalled")) {
1230                 if (!strcasecmp(val, "vars")) {
1231                         q->eventwhencalled = QUEUE_EVENT_VARIABLES;
1232                 } else {
1233                         q->eventwhencalled = ast_true(val) ? 1 : 0;
1234                 }
1235         } else if (!strcasecmp(param, "reportholdtime")) {
1236                 q->reportholdtime = ast_true(val);
1237         } else if (!strcasecmp(param, "memberdelay")) {
1238                 q->memberdelay = atoi(val);
1239         } else if (!strcasecmp(param, "weight")) {
1240                 q->weight = atoi(val);
1241                 if (q->weight)
1242                         use_weight++;
1243                 /* With Realtime queues, if the last queue using weights is deleted in realtime,
1244                    we will not see any effect on use_weight until next reload. */
1245         } else if (!strcasecmp(param, "timeoutrestart")) {
1246                 q->timeoutrestart = ast_true(val);
1247         } else if (!strcasecmp(param, "defaultrule")) {
1248                 ast_string_field_set(q, defaultrule, val);
1249         } else if (failunknown) {
1250                 if (linenum >= 0) {
1251                         ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queues.conf\n",
1252                                 q->name, param, linenum);
1253                 } else {
1254                         ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s\n", q->name, param);
1255                 }
1256         }
1257 }
1258
1259 static void rt_handle_member_record(struct call_queue *q, char *interface, const char *membername, const char *penalty_str, const char *paused_str)
1260 {
1261         struct member *m, tmpmem;
1262         int penalty = 0;
1263         int paused  = 0;
1264
1265         if (penalty_str) {
1266                 penalty = atoi(penalty_str);
1267                 if (penalty < 0)
1268                         penalty = 0;
1269         }
1270
1271         if (paused_str) {
1272                 paused = atoi(paused_str);
1273                 if (paused < 0)
1274                         paused = 0;
1275         }
1276
1277         /* Find the member, or the place to put a new one. */
1278         ast_copy_string(tmpmem.interface, interface, sizeof(tmpmem.interface));
1279         m = ao2_find(q->members, &tmpmem, OBJ_POINTER);
1280
1281         /* Create a new one if not found, else update penalty */
1282         if (!m) {
1283                 if ((m = create_queue_member(interface, membername, penalty, paused))) {
1284                         m->dead = 0;
1285                         m->realtime = 1;
1286                         add_to_interfaces(interface);
1287                         ao2_link(q->members, m);
1288                         ao2_ref(m, -1);
1289                         m = NULL;
1290                         q->membercount++;
1291                 }
1292         } else {
1293                 m->dead = 0;    /* Do not delete this one. */
1294                 if (paused_str)
1295                         m->paused = paused;
1296                 m->penalty = penalty;
1297                 ao2_ref(m, -1);
1298         }
1299 }
1300
1301 static void free_members(struct call_queue *q, int all)
1302 {
1303         /* Free non-dynamic members */
1304         struct member *cur;
1305         struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
1306
1307         while ((cur = ao2_iterator_next(&mem_iter))) {
1308                 if (all || !cur->dynamic) {
1309                         ao2_unlink(q->members, cur);
1310                         remove_from_interfaces(cur->interface);
1311                         q->membercount--;
1312                 }
1313                 ao2_ref(cur, -1);
1314         }
1315 }
1316
1317 static void destroy_queue(void *obj)
1318 {
1319         struct call_queue *q = obj;
1320         int i;
1321
1322         ast_debug(0, "Queue destructor called for queue '%s'!\n", q->name);
1323
1324         free_members(q, 1);
1325         ast_string_field_free_memory(q);
1326         for (i = 0; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
1327                 if (q->sound_periodicannounce[i])
1328                         free(q->sound_periodicannounce[i]);
1329         }
1330         ao2_ref(q->members, -1);
1331 }
1332
1333 static struct call_queue *alloc_queue(const char *queuename)
1334 {
1335         struct call_queue *q;
1336
1337         if ((q = ao2_alloc(sizeof(*q), destroy_queue))) {
1338                 if (ast_string_field_init(q, 64)) {
1339                         free(q);
1340                         return NULL;
1341                 }
1342                 ast_string_field_set(q, name, queuename);
1343         }
1344         return q;
1345 }
1346
1347 /*!\brief Reload a single queue via realtime.
1348    \return Return the queue, or NULL if it doesn't exist.
1349    \note Should be called with the global qlock locked. */
1350 static struct call_queue *find_queue_by_name_rt(const char *queuename, struct ast_variable *queue_vars, struct ast_config *member_config)
1351 {
1352         struct ast_variable *v;
1353         struct call_queue *q, tmpq = {
1354                 .name = queuename,      
1355         };
1356         struct member *m;
1357         struct ao2_iterator mem_iter;
1358         char *interface = NULL;
1359         const char *tmp_name;
1360         char *tmp;
1361         char tmpbuf[64];        /* Must be longer than the longest queue param name. */
1362
1363         /* Static queues override realtime. */
1364         if ((q = ao2_find(queues, &tmpq, OBJ_POINTER))) {
1365                 ao2_lock(q);
1366                 if (!q->realtime) {
1367                         if (q->dead) {
1368                                 ao2_unlock(q);
1369                                 queue_unref(q);
1370                                 return NULL;
1371                         } else {
1372                                 ast_log(LOG_WARNING, "Static queue '%s' already exists. Not loading from realtime\n", q->name);
1373                                 ao2_unlock(q);
1374                                 return q;
1375                         }
1376                 }
1377                 queue_unref(q);
1378         } else if (!member_config)
1379                 /* Not found in the list, and it's not realtime ... */
1380                 return NULL;
1381
1382         /* Check if queue is defined in realtime. */
1383         if (!queue_vars) {
1384                 /* Delete queue from in-core list if it has been deleted in realtime. */
1385                 if (q) {
1386                         /*! \note Hmm, can't seem to distinguish a DB failure from a not
1387                            found condition... So we might delete an in-core queue
1388                            in case of DB failure. */
1389                         ast_debug(1, "Queue %s not found in realtime.\n", queuename);
1390
1391                         q->dead = 1;
1392                         /* Delete if unused (else will be deleted when last caller leaves). */
1393                         ao2_unlink(queues, q);
1394                         ao2_unlock(q);
1395                         queue_unref(q);
1396                 }
1397                 return NULL;
1398         }
1399
1400         /* Create a new queue if an in-core entry does not exist yet. */
1401         if (!q) {
1402                 if (!(q = alloc_queue(queuename)))
1403                         return NULL;
1404                 ao2_lock(q);
1405                 clear_queue(q);
1406                 q->realtime = 1;
1407                 init_queue(q);          /* Ensure defaults for all parameters not set explicitly. */
1408                 ao2_link(queues, q);
1409         }
1410
1411         memset(tmpbuf, 0, sizeof(tmpbuf));
1412         for (v = queue_vars; v; v = v->next) {
1413                 /* Convert to dashes `-' from underscores `_' as the latter are more SQL friendly. */
1414                 if ((tmp = strchr(v->name, '_'))) {
1415                         ast_copy_string(tmpbuf, v->name, sizeof(tmpbuf));
1416                         tmp_name = tmpbuf;
1417                         tmp = tmpbuf;
1418                         while ((tmp = strchr(tmp, '_')))
1419                                 *tmp++ = '-';
1420                 } else
1421                         tmp_name = v->name;
1422                 queue_set_param(q, tmp_name, v->value, -1, 0);
1423         }
1424
1425         /* Temporarily set realtime members dead so we can detect deleted ones. 
1426          * Also set the membercount correctly for realtime*/
1427         mem_iter = ao2_iterator_init(q->members, 0);
1428         while ((m = ao2_iterator_next(&mem_iter))) {
1429                 q->membercount++;
1430                 if (m->realtime)
1431                         m->dead = 1;
1432                 ao2_ref(m, -1);
1433         }
1434
1435         while ((interface = ast_category_browse(member_config, interface))) {
1436                 rt_handle_member_record(q, interface,
1437                         ast_variable_retrieve(member_config, interface, "membername"),
1438                         ast_variable_retrieve(member_config, interface, "penalty"),
1439                         ast_variable_retrieve(member_config, interface, "paused"));
1440         }
1441
1442         /* Delete all realtime members that have been deleted in DB. */
1443         mem_iter = ao2_iterator_init(q->members, 0);
1444         while ((m = ao2_iterator_next(&mem_iter))) {
1445                 if (m->dead) {
1446                         ao2_unlink(q->members, m);
1447                         ao2_unlock(q);
1448                         remove_from_interfaces(m->interface);
1449                         ao2_lock(q);
1450                         q->membercount--;
1451                 }
1452                 ao2_ref(m, -1);
1453         }
1454
1455         ao2_unlock(q);
1456
1457         return q;
1458 }
1459
1460 static struct call_queue *load_realtime_queue(const char *queuename)
1461 {
1462         struct ast_variable *queue_vars;
1463         struct ast_config *member_config = NULL;
1464         struct call_queue *q = NULL, tmpq = {
1465                 .name = queuename,      
1466         };
1467
1468         /* Find the queue in the in-core list first. */
1469         q = ao2_find(queues, &tmpq, OBJ_POINTER);
1470
1471         if (!q || q->realtime) {
1472                 /*! \note Load from realtime before taking the global qlock, to avoid blocking all
1473                    queue operations while waiting for the DB.
1474
1475                    This will be two separate database transactions, so we might
1476                    see queue parameters as they were before another process
1477                    changed the queue and member list as it was after the change.
1478                    Thus we might see an empty member list when a queue is
1479                    deleted. In practise, this is unlikely to cause a problem. */
1480
1481                 queue_vars = ast_load_realtime("queues", "name", queuename, NULL);
1482                 if (queue_vars) {
1483                         member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", queuename, NULL);
1484                         if (!member_config) {
1485                                 ast_log(LOG_ERROR, "no queue_members defined in your config (extconfig.conf).\n");
1486                                 ast_variables_destroy(queue_vars);
1487                                 return NULL;
1488                         }
1489                 }
1490
1491                 ao2_lock(queues);
1492                 q = find_queue_by_name_rt(queuename, queue_vars, member_config);
1493                 if (member_config)
1494                         ast_config_destroy(member_config);
1495                 if (queue_vars)
1496                         ast_variables_destroy(queue_vars);
1497                 ao2_unlock(queues);
1498
1499         } else {
1500                 update_realtime_members(q);
1501         }
1502         return q;
1503 }
1504
1505 static int update_realtime_member_field(struct member *mem, const char *queue_name, const char *field, const char *value)
1506 {
1507         struct ast_variable *var;
1508         int ret = -1;
1509
1510         if (!(var = ast_load_realtime("queue_members", "interface", mem->interface, "queue_name", queue_name, NULL))) 
1511                 return ret;
1512         while (var) {
1513                 if (!strcmp(var->name, "uniqueid"))
1514                         break;
1515                 var = var->next;
1516         }
1517         if (var && !ast_strlen_zero(var->value)) {
1518                 if ((ast_update_realtime("queue_members", "uniqueid", var->value, field, value, NULL)) > -1)
1519                         ret = 0;
1520         }
1521         return ret;
1522 }
1523
1524 static void update_realtime_members(struct call_queue *q)
1525 {
1526         struct ast_config *member_config = NULL;
1527         struct member *m;
1528         char *interface = NULL;
1529         struct ao2_iterator mem_iter;
1530
1531         member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", q->name , NULL);
1532         if (!member_config) {
1533                 /*This queue doesn't have realtime members*/
1534                 ast_debug(3, "Queue %s has no realtime members defined. No need for update\n", q->name);
1535                 return;
1536         }
1537
1538         ao2_lock(q);
1539         
1540         /* Temporarily set realtime  members dead so we can detect deleted ones.*/ 
1541         mem_iter = ao2_iterator_init(q->members, 0);
1542         while ((m = ao2_iterator_next(&mem_iter))) {
1543                 if (m->realtime)
1544                         m->dead = 1;
1545                 ao2_ref(m, -1);
1546         }
1547
1548         while ((interface = ast_category_browse(member_config, interface))) {
1549                 rt_handle_member_record(q, interface,
1550                         S_OR(ast_variable_retrieve(member_config, interface, "membername"), interface),
1551                         ast_variable_retrieve(member_config, interface, "penalty"),
1552                         ast_variable_retrieve(member_config, interface, "paused"));
1553         }
1554
1555         /* Delete all realtime members that have been deleted in DB. */
1556         mem_iter = ao2_iterator_init(q->members, 0);
1557         while ((m = ao2_iterator_next(&mem_iter))) {
1558                 if (m->dead) {
1559                         ao2_unlink(q->members, m);
1560                         ao2_unlock(q);
1561                         remove_from_interfaces(m->interface);
1562                         ao2_lock(q);
1563                         q->membercount--;
1564                 }
1565                 ao2_ref(m, -1);
1566         }
1567         ao2_unlock(q);
1568 }
1569
1570 static int join_queue(char *queuename, struct queue_ent *qe, enum queue_result *reason)
1571 {
1572         struct call_queue *q;
1573         struct queue_ent *cur, *prev = NULL;
1574         int res = -1;
1575         int pos = 0;
1576         int inserted = 0;
1577         enum queue_member_status stat;
1578
1579         if (!(q = load_realtime_queue(queuename)))
1580                 return res;
1581
1582         ao2_lock(queues);
1583         ao2_lock(q);
1584
1585         /* This is our one */
1586         stat = get_member_status(q, qe->max_penalty, qe->min_penalty);
1587         if (!q->joinempty && (stat == QUEUE_NO_MEMBERS))
1588                 *reason = QUEUE_JOINEMPTY;
1589         else if ((q->joinempty == QUEUE_EMPTY_STRICT) && (stat == QUEUE_NO_REACHABLE_MEMBERS || stat == QUEUE_NO_UNPAUSED_REACHABLE_MEMBERS))
1590                 *reason = QUEUE_JOINUNAVAIL;
1591         else if ((q->joinempty == QUEUE_EMPTY_LOOSE) && (stat == QUEUE_NO_REACHABLE_MEMBERS))
1592                 *reason = QUEUE_JOINUNAVAIL;
1593         else if (q->maxlen && (q->count >= q->maxlen))
1594                 *reason = QUEUE_FULL;
1595         else {
1596                 /* There's space for us, put us at the right position inside
1597                  * the queue.
1598                  * Take into account the priority of the calling user */
1599                 inserted = 0;
1600                 prev = NULL;
1601                 cur = q->head;
1602                 while (cur) {
1603                         /* We have higher priority than the current user, enter
1604                          * before him, after all the other users with priority
1605                          * higher or equal to our priority. */
1606                         if ((!inserted) && (qe->prio > cur->prio)) {
1607                                 insert_entry(q, prev, qe, &pos);
1608                                 inserted = 1;
1609                         }
1610                         cur->pos = ++pos;
1611                         prev = cur;
1612                         cur = cur->next;
1613                 }
1614                 /* No luck, join at the end of the queue */
1615                 if (!inserted)
1616                         insert_entry(q, prev, qe, &pos);
1617                 ast_copy_string(qe->moh, q->moh, sizeof(qe->moh));
1618                 ast_copy_string(qe->announce, q->announce, sizeof(qe->announce));
1619                 ast_copy_string(qe->context, q->context, sizeof(qe->context));
1620                 q->count++;
1621                 res = 0;
1622                 manager_event(EVENT_FLAG_CALL, "Join",
1623                         "Channel: %s\r\nCallerID: %s\r\nCallerIDName: %s\r\nQueue: %s\r\nPosition: %d\r\nCount: %d\r\nUniqueid: %s\r\n",
1624                         qe->chan->name,
1625                         S_OR(qe->chan->cid.cid_num, "unknown"), /* XXX somewhere else it is <unknown> */
1626                         S_OR(qe->chan->cid.cid_name, "unknown"),
1627                         q->name, qe->pos, q->count, qe->chan->uniqueid );
1628                 ast_debug(1, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, qe->chan->name, qe->pos );
1629         }
1630         ao2_unlock(q);
1631         ao2_unlock(queues);
1632
1633         return res;
1634 }
1635
1636 static int play_file(struct ast_channel *chan, const char *filename)
1637 {
1638         int res;
1639
1640         ast_stopstream(chan);
1641
1642         res = ast_streamfile(chan, filename, chan->language);
1643         if (!res)
1644                 res = ast_waitstream(chan, AST_DIGIT_ANY);
1645
1646         ast_stopstream(chan);
1647
1648         return res;
1649 }
1650
1651 static int valid_exit(struct queue_ent *qe, char digit)
1652 {
1653         int digitlen = strlen(qe->digits);
1654
1655         /* Prevent possible buffer overflow */
1656         if (digitlen < sizeof(qe->digits) - 2) {
1657                 qe->digits[digitlen] = digit;
1658                 qe->digits[digitlen + 1] = '\0';
1659         } else {
1660                 qe->digits[0] = '\0';
1661                 return 0;
1662         }
1663
1664         /* If there's no context to goto, short-circuit */
1665         if (ast_strlen_zero(qe->context))
1666                 return 0;
1667
1668         /* If the extension is bad, then reset the digits to blank */
1669         if (!ast_canmatch_extension(qe->chan, qe->context, qe->digits, 1, qe->chan->cid.cid_num)) {
1670                 qe->digits[0] = '\0';
1671                 return 0;
1672         }
1673
1674         /* We have an exact match */
1675         if (!ast_goto_if_exists(qe->chan, qe->context, qe->digits, 1)) {
1676                 qe->valid_digits = 1;
1677                 /* Return 1 on a successful goto */
1678                 return 1;
1679         }
1680
1681         return 0;
1682 }
1683
1684 static int say_position(struct queue_ent *qe, int ringing)
1685 {
1686         int res = 0, avgholdmins, avgholdsecs;
1687         time_t now;
1688
1689         /* Let minannouncefrequency seconds pass between the start of each position announcement */
1690         time(&now);
1691         if ((now - qe->last_pos) < qe->parent->minannouncefrequency)
1692                 return 0;
1693
1694         /* If either our position has changed, or we are over the freq timer, say position */
1695         if ((qe->last_pos_said == qe->pos) && ((now - qe->last_pos) < qe->parent->announcefrequency))
1696                 return 0;
1697
1698         if (ringing) {
1699                 ast_indicate(qe->chan,-1);
1700         } else {
1701                 ast_moh_stop(qe->chan);
1702         }
1703         if (qe->parent->announceposition) {
1704                 /* Say we're next, if we are */
1705                 if (qe->pos == 1) {
1706                         res = play_file(qe->chan, qe->parent->sound_next);
1707                         if (res)
1708                                 goto playout;
1709                         else
1710                                 goto posout;
1711                 } else {
1712                         res = play_file(qe->chan, qe->parent->sound_thereare);
1713                         if (res)
1714                                 goto playout;
1715                         res = ast_say_number(qe->chan, qe->pos, AST_DIGIT_ANY, qe->chan->language, NULL); /* Needs gender */
1716                         if (res)
1717                                 goto playout;
1718                         res = play_file(qe->chan, qe->parent->sound_calls);
1719                         if (res)
1720                                 goto playout;
1721                 }
1722         }
1723         /* Round hold time to nearest minute */
1724         avgholdmins = abs(((qe->parent->holdtime + 30) - (now - qe->start)) / 60);
1725
1726         /* If they have specified a rounding then round the seconds as well */
1727         if (qe->parent->roundingseconds) {
1728                 avgholdsecs = (abs(((qe->parent->holdtime + 30) - (now - qe->start))) - 60 * avgholdmins) / qe->parent->roundingseconds;
1729                 avgholdsecs *= qe->parent->roundingseconds;
1730         } else {
1731                 avgholdsecs = 0;
1732         }
1733
1734         ast_verb(3, "Hold time for %s is %d minutes %d seconds\n", qe->parent->name, avgholdmins, avgholdsecs);
1735
1736         /* If the hold time is >1 min, if it's enabled, and if it's not
1737            supposed to be only once and we have already said it, say it */
1738         if ((avgholdmins+avgholdsecs) > 0 && (qe->parent->announceholdtime) &&
1739                 (!(qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE) && qe->last_pos)) {
1740                 res = play_file(qe->chan, qe->parent->sound_holdtime);
1741                 if (res)
1742                         goto playout;
1743
1744                 if (avgholdmins > 0) {
1745                         if (avgholdmins < 2) {
1746                                 res = play_file(qe->chan, qe->parent->sound_lessthan);
1747                                 if (res)
1748                                         goto playout;
1749
1750                                 res = ast_say_number(qe->chan, 2, AST_DIGIT_ANY, qe->chan->language, NULL);
1751                                 if (res)
1752                                         goto playout;
1753                         } else {
1754                                 res = ast_say_number(qe->chan, avgholdmins, AST_DIGIT_ANY, qe->chan->language, NULL);
1755                                 if (res)
1756                                         goto playout;
1757                         }
1758                         
1759                         res = play_file(qe->chan, qe->parent->sound_minutes);
1760                         if (res)
1761                                 goto playout;
1762                 }
1763                 if (avgholdsecs>0) {
1764                         res = ast_say_number(qe->chan, avgholdsecs, AST_DIGIT_ANY, qe->chan->language, NULL);
1765                         if (res)
1766                                 goto playout;
1767
1768                         res = play_file(qe->chan, qe->parent->sound_seconds);
1769                         if (res)
1770                                 goto playout;
1771                 }
1772
1773         }
1774
1775 posout:
1776         if (qe->parent->announceposition) {
1777                 ast_verb(3, "Told %s in %s their queue position (which was %d)\n",
1778                         qe->chan->name, qe->parent->name, qe->pos);
1779         }
1780         res = play_file(qe->chan, qe->parent->sound_thanks);
1781
1782 playout:
1783         if ((res > 0 && !valid_exit(qe, res)) || res < 0)
1784                 res = 0;
1785
1786         /* Set our last_pos indicators */
1787         qe->last_pos = now;
1788         qe->last_pos_said = qe->pos;
1789
1790         /* Don't restart music on hold if we're about to exit the caller from the queue */
1791         if (!res) {
1792                 if (ringing)
1793                         ast_indicate(qe->chan, AST_CONTROL_RINGING);
1794                 else
1795                         ast_moh_start(qe->chan, qe->moh, NULL);
1796         }
1797         return res;
1798 }
1799
1800 static void recalc_holdtime(struct queue_ent *qe, int newholdtime)
1801 {
1802         int oldvalue;
1803
1804         /* Calculate holdtime using a recursive boxcar filter */
1805         /* Thanks to SRT for this contribution */
1806         /* 2^2 (4) is the filter coefficient; a higher exponent would give old entries more weight */
1807
1808         ao2_lock(qe->parent);
1809         oldvalue = qe->parent->holdtime;
1810         qe->parent->holdtime = (((oldvalue << 2) - oldvalue) + newholdtime) >> 2;
1811         ao2_unlock(qe->parent);
1812 }
1813
1814
1815 static void leave_queue(struct queue_ent *qe)
1816 {
1817         struct call_queue *q;
1818         struct queue_ent *cur, *prev = NULL;
1819         struct penalty_rule *pr_iter;
1820         int pos = 0;
1821
1822         if (!(q = qe->parent))
1823                 return;
1824         queue_ref(q);
1825         ao2_lock(q);
1826
1827         prev = NULL;
1828         for (cur = q->head; cur; cur = cur->next) {
1829                 if (cur == qe) {
1830                         q->count--;
1831
1832                         /* Take us out of the queue */
1833                         manager_event(EVENT_FLAG_CALL, "Leave",
1834                                 "Channel: %s\r\nQueue: %s\r\nCount: %d\r\nUniqueid: %s\r\n",
1835                                 qe->chan->name, q->name,  q->count, qe->chan->uniqueid);
1836                         ast_debug(1, "Queue '%s' Leave, Channel '%s'\n", q->name, qe->chan->name );
1837                         /* Take us out of the queue */
1838                         if (prev)
1839                                 prev->next = cur->next;
1840                         else
1841                                 q->head = cur->next;
1842                         /* Free penalty rules */
1843                         while ((pr_iter = AST_LIST_REMOVE_HEAD(&qe->qe_rules, list)))
1844                                 ast_free(pr_iter);
1845                 } else {
1846                         /* Renumber the people after us in the queue based on a new count */
1847                         cur->pos = ++pos;
1848                         prev = cur;
1849                 }
1850         }
1851         ao2_unlock(q);
1852
1853         /*If the queue is a realtime queue, check to see if it's still defined in real time*/
1854         if (q->realtime) {
1855                 if (!ast_load_realtime("queues", "name", q->name, NULL))
1856                         q->dead = 1;
1857         }
1858
1859         if (q->dead) {  
1860                 /* It's dead and nobody is in it, so kill it */
1861                 ao2_unlink(queues, q);
1862                 queue_unref(q);
1863         }
1864         queue_unref(q);
1865 }
1866
1867 /* Hang up a list of outgoing calls */
1868 static void hangupcalls(struct callattempt *outgoing, struct ast_channel *exception)
1869 {
1870         struct callattempt *oo;
1871
1872         while (outgoing) {
1873                 /* Hangup any existing lines we have open */
1874                 if (outgoing->chan && (outgoing->chan != exception))
1875                         ast_hangup(outgoing->chan);
1876                 oo = outgoing;
1877                 outgoing = outgoing->q_next;
1878                 if (oo->member)
1879                         ao2_ref(oo->member, -1);
1880                 ast_free(oo);
1881         }
1882 }
1883
1884 static int update_status(struct call_queue *q, struct member *member, int status)
1885 {
1886         struct member *cur;
1887         struct ao2_iterator mem_iter;
1888
1889         /* Since a reload could have taken place, we have to traverse the list to
1890                 be sure it's still valid */
1891         ao2_lock(q);
1892         mem_iter = ao2_iterator_init(q->members, 0);
1893         while ((cur = ao2_iterator_next(&mem_iter))) {
1894                 if (member != cur) {
1895                         ao2_ref(cur, -1);
1896                         continue;
1897                 }
1898
1899                 cur->status = status;
1900                 if (!q->maskmemberstatus) {
1901                         manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
1902                                 "Queue: %s\r\n"
1903                                 "Location: %s\r\n"
1904                                 "MemberName: %s\r\n"
1905                                 "Membership: %s\r\n"
1906                                 "Penalty: %d\r\n"
1907                                 "CallsTaken: %d\r\n"
1908                                 "LastCall: %d\r\n"
1909                                 "Status: %d\r\n"
1910                                 "Paused: %d\r\n",
1911                                 q->name, cur->interface, cur->membername, cur->dynamic ? "dynamic" : cur->realtime ? "realtime": "static",
1912                                 cur->penalty, cur->calls, (int)cur->lastcall, cur->status, cur->paused);
1913                 }
1914                 ao2_ref(cur, -1);
1915         }
1916         ao2_unlock(q);
1917         return 0;
1918 }
1919
1920 static int update_dial_status(struct call_queue *q, struct member *member, int status)
1921 {
1922         if (status == AST_CAUSE_BUSY)
1923                 status = AST_DEVICE_BUSY;
1924         else if (status == AST_CAUSE_UNREGISTERED)
1925                 status = AST_DEVICE_UNAVAILABLE;
1926         else if (status == AST_CAUSE_NOSUCHDRIVER)
1927                 status = AST_DEVICE_INVALID;
1928         else
1929                 status = AST_DEVICE_UNKNOWN;
1930         return update_status(q, member, status);
1931 }
1932
1933 /* traverse all defined queues which have calls waiting and contain this member
1934    return 0 if no other queue has precedence (higher weight) or 1 if found  */
1935 static int compare_weight(struct call_queue *rq, struct member *member)
1936 {
1937         struct call_queue *q;
1938         struct member *mem;
1939         int found = 0;
1940         struct ao2_iterator queue_iter;
1941         
1942         /* &qlock and &rq->lock already set by try_calling()
1943          * to solve deadlock */
1944         queue_iter = ao2_iterator_init(queues, 0);
1945         while ((q = ao2_iterator_next(&queue_iter))) {
1946                 if (q == rq) { /* don't check myself, could deadlock */
1947                         queue_unref(q);
1948                         continue;
1949                 }
1950                 ao2_lock(q);
1951                 if (q->count && q->members) {
1952                         if ((mem = ao2_find(q->members, member, OBJ_POINTER))) {
1953                                 ast_debug(1, "Found matching member %s in queue '%s'\n", mem->interface, q->name);
1954                                 if (q->weight > rq->weight) {
1955                                         ast_debug(1, "Queue '%s' (weight %d, calls %d) is preferred over '%s' (weight %d, calls %d)\n", q->name, q->weight, q->count, rq->name, rq->weight, rq->count);
1956                                         found = 1;
1957                                 }
1958                                 ao2_ref(mem, -1);
1959                         }
1960                 }
1961                 ao2_unlock(q);
1962                 if (found) {
1963                         queue_unref(q);
1964                         break;
1965                 }
1966                 queue_unref(q);
1967         }
1968         return found;
1969 }
1970
1971 /*! \brief common hangup actions */
1972 static void do_hang(struct callattempt *o)
1973 {
1974         o->stillgoing = 0;
1975         ast_hangup(o->chan);
1976         o->chan = NULL;
1977 }
1978
1979 static char *vars2manager(struct ast_channel *chan, char *vars, size_t len)
1980 {
1981         struct ast_str *buf = ast_str_alloca(len + 1);
1982         char *tmp;
1983
1984         if (pbx_builtin_serialize_variables(chan, &buf)) {
1985                 int i, j;
1986
1987                 /* convert "\n" to "\nVariable: " */
1988                 strcpy(vars, "Variable: ");
1989                 tmp = buf->str;
1990
1991                 for (i = 0, j = 10; (i < len - 1) && (j < len - 1); i++, j++) {
1992                         vars[j] = tmp[i];
1993
1994                         if (tmp[i + 1] == '\0')
1995                                 break;
1996                         if (tmp[i] == '\n') {
1997                                 vars[j++] = '\r';
1998                                 vars[j++] = '\n';
1999
2000                                 ast_copy_string(&(vars[j]), "Variable: ", len - j);
2001                                 j += 9;
2002                         }
2003                 }
2004                 if (j > len - 1)
2005                         j = len - 1;
2006                 vars[j - 2] = '\r';
2007                 vars[j - 1] = '\n';
2008                 vars[j] = '\0';
2009         } else {
2010                 /* there are no channel variables; leave it blank */
2011                 *vars = '\0';
2012         }
2013         return vars;
2014 }
2015
2016 static int ring_entry(struct queue_ent *qe, struct callattempt *tmp, int *busies)
2017 {
2018         int res;
2019         int status;
2020         char tech[256];
2021         char *location;
2022
2023         /* on entry here, we know that tmp->chan == NULL */
2024         if ((tmp->lastqueue && tmp->lastqueue->wrapuptime && (time(NULL) - tmp->lastcall < tmp->lastqueue->wrapuptime)) ||
2025                 (!tmp->lastqueue && qe->parent->wrapuptime && (time(NULL) - tmp->lastcall < qe->parent->wrapuptime))) {
2026                 ast_debug(1, "Wrapuptime not yet expired on queue %s for %s\n", 
2027                                 (tmp->lastqueue ? tmp->lastqueue->name : qe->parent->name), tmp->interface);
2028                 if (qe->chan->cdr)
2029                         ast_cdr_busy(qe->chan->cdr);
2030                 tmp->stillgoing = 0;
2031                 (*busies)++;
2032                 return 0;
2033         }
2034
2035         if (!qe->parent->ringinuse && (tmp->member->status != AST_DEVICE_NOT_INUSE) && (tmp->member->status != AST_DEVICE_UNKNOWN)) {
2036                 ast_debug(1, "%s in use, can't receive call\n", tmp->interface);
2037                 if (qe->chan->cdr)
2038                         ast_cdr_busy(qe->chan->cdr);
2039                 tmp->stillgoing = 0;
2040                 return 0;
2041         }
2042
2043         if (tmp->member->paused) {
2044                 ast_debug(1, "%s paused, can't receive call\n", tmp->interface);
2045                 if (qe->chan->cdr)
2046                         ast_cdr_busy(qe->chan->cdr);
2047                 tmp->stillgoing = 0;
2048                 return 0;
2049         }
2050         if (use_weight && compare_weight(qe->parent,tmp->member)) {
2051                 ast_debug(1, "Priority queue delaying call to %s:%s\n", qe->parent->name, tmp->interface);
2052                 if (qe->chan->cdr)
2053                         ast_cdr_busy(qe->chan->cdr);
2054                 tmp->stillgoing = 0;
2055                 (*busies)++;
2056                 return 0;
2057         }
2058
2059         ast_copy_string(tech, tmp->interface, sizeof(tech));
2060         if ((location = strchr(tech, '/')))
2061                 *location++ = '\0';
2062         else
2063                 location = "";
2064
2065         /* Request the peer */
2066         tmp->chan = ast_request(tech, qe->chan->nativeformats, location, &status);
2067         if (!tmp->chan) {                       /* If we can't, just go on to the next call */
2068                 if (qe->chan->cdr)
2069                         ast_cdr_busy(qe->chan->cdr);
2070                 tmp->stillgoing = 0;
2071                 update_dial_status(qe->parent, tmp->member, status);
2072
2073                 ao2_lock(qe->parent);
2074                 qe->parent->rrpos++;
2075                 qe->linpos++;
2076                 ao2_unlock(qe->parent);
2077
2078
2079                 (*busies)++;
2080                 return 0;
2081         } else if (status != tmp->oldstatus)
2082                 update_dial_status(qe->parent, tmp->member, status);
2083         
2084         tmp->chan->appl = "AppQueue";
2085         tmp->chan->data = "(Outgoing Line)";
2086         tmp->chan->whentohangup = 0;
2087         if (tmp->chan->cid.cid_num)
2088                 ast_free(tmp->chan->cid.cid_num);
2089         tmp->chan->cid.cid_num = ast_strdup(qe->chan->cid.cid_num);
2090         if (tmp->chan->cid.cid_name)
2091                 ast_free(tmp->chan->cid.cid_name);
2092         tmp->chan->cid.cid_name = ast_strdup(qe->chan->cid.cid_name);
2093         if (tmp->chan->cid.cid_ani)
2094                 ast_free(tmp->chan->cid.cid_ani);
2095         tmp->chan->cid.cid_ani = ast_strdup(qe->chan->cid.cid_ani);
2096
2097         /* Inherit specially named variables from parent channel */
2098         ast_channel_inherit_variables(qe->chan, tmp->chan);
2099
2100         /* Presense of ADSI CPE on outgoing channel follows ours */
2101         tmp->chan->adsicpe = qe->chan->adsicpe;
2102
2103         /* Place the call, but don't wait on the answer */
2104         if ((res = ast_call(tmp->chan, location, 0))) {
2105                 /* Again, keep going even if there's an error */
2106                 ast_debug(1, "ast call on peer returned %d\n", res);
2107                 ast_verb(3, "Couldn't call %s\n", tmp->interface);
2108                 do_hang(tmp);
2109                 (*busies)++;
2110                 return 0;
2111         } else if (qe->parent->eventwhencalled) {
2112                 char vars[2048];
2113
2114                 manager_event(EVENT_FLAG_AGENT, "AgentCalled",
2115                                         "Queue: %s\r\n"
2116                                         "AgentCalled: %s\r\n"
2117                                         "AgentName: %s\r\n"
2118                                         "ChannelCalling: %s\r\n"
2119                                         "DestinationChannel: %s\r\n"
2120                                         "CallerIDNum: %s\r\n"
2121                                         "CallerIDName: %s\r\n"
2122                                         "Context: %s\r\n"
2123                                         "Extension: %s\r\n"
2124                                         "Priority: %d\r\n"
2125                                         "%s",
2126                                         qe->parent->name, tmp->interface, tmp->member->membername, qe->chan->name, tmp->chan->name,
2127                                         tmp->chan->cid.cid_num ? tmp->chan->cid.cid_num : "unknown",
2128                                         tmp->chan->cid.cid_name ? tmp->chan->cid.cid_name : "unknown",
2129                                         qe->chan->context, qe->chan->exten, qe->chan->priority,
2130                                         qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
2131                 ast_verb(3, "Called %s\n", tmp->interface);
2132         }
2133
2134         return 1;
2135 }
2136
2137 /*! \brief find the entry with the best metric, or NULL */
2138 static struct callattempt *find_best(struct callattempt *outgoing)
2139 {
2140         struct callattempt *best = NULL, *cur;
2141
2142         for (cur = outgoing; cur; cur = cur->q_next) {
2143                 if (cur->stillgoing &&                                  /* Not already done */
2144                         !cur->chan &&                                   /* Isn't already going */
2145                         (!best || cur->metric < best->metric)) {                /* We haven't found one yet, or it's better */
2146                         best = cur;
2147                 }
2148         }
2149
2150         return best;
2151 }
2152
2153 static int ring_one(struct queue_ent *qe, struct callattempt *outgoing, int *busies)
2154 {
2155         int ret = 0;
2156
2157         while (ret == 0) {
2158                 struct callattempt *best = find_best(outgoing);
2159                 if (!best) {
2160                         ast_debug(1, "Nobody left to try ringing in queue\n");
2161                         break;
2162                 }
2163                 if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
2164                         struct callattempt *cur;
2165                         /* Ring everyone who shares this best metric (for ringall) */
2166                         for (cur = outgoing; cur; cur = cur->q_next) {
2167                                 if (cur->stillgoing && !cur->chan && cur->metric <= best->metric) {
2168                                         ast_debug(1, "(Parallel) Trying '%s' with metric %d\n", cur->interface, cur->metric);
2169                                         ret |= ring_entry(qe, cur, busies);
2170                                 }
2171                         }
2172                 } else {
2173                         /* Ring just the best channel */
2174                         ast_debug(1, "Trying '%s' with metric %d\n", best->interface, best->metric);
2175                         ret = ring_entry(qe, best, busies);
2176                 }
2177         }
2178
2179         return ret;
2180 }
2181
2182 static int store_next_rr(struct queue_ent *qe, struct callattempt *outgoing)
2183 {
2184         struct callattempt *best = find_best(outgoing);
2185
2186         if (best) {
2187                 /* Ring just the best channel */
2188                 ast_debug(1, "Next is '%s' with metric %d\n", best->interface, best->metric);
2189                 qe->parent->rrpos = best->metric % 1000;
2190         } else {
2191                 /* Just increment rrpos */
2192                 if (qe->parent->wrapped) {
2193                         /* No more channels, start over */
2194                         qe->parent->rrpos = 0;
2195                 } else {
2196                         /* Prioritize next entry */
2197                         qe->parent->rrpos++;
2198                 }
2199         }
2200         qe->parent->wrapped = 0;
2201
2202         return 0;
2203 }
2204
2205 static int store_next_lin(struct queue_ent *qe, struct callattempt *outgoing)
2206 {
2207         struct callattempt *best = find_best(outgoing);
2208
2209         if (best) {
2210                 /* Ring just the best channel */
2211                 ast_debug(1, "Next is '%s' with metric %d\n", best->interface, best->metric);
2212                 qe->linpos = best->metric % 1000;
2213         } else {
2214                 /* Just increment rrpos */
2215                 if (qe->linwrapped) {
2216                         /* No more channels, start over */
2217                         qe->linpos = 0;
2218                 } else {
2219                         /* Prioritize next entry */
2220                         qe->linpos++;
2221                 }
2222         }
2223         qe->linwrapped = 0;
2224
2225         return 0;
2226 }
2227
2228 static int say_periodic_announcement(struct queue_ent *qe, int ringing)
2229 {
2230         int res = 0;
2231         time_t now;
2232
2233         /* Get the current time */
2234         time(&now);
2235
2236         /* Check to see if it is time to announce */
2237         if ((now - qe->last_periodic_announce_time) < qe->parent->periodicannouncefrequency)
2238                 return 0;
2239
2240         /* Stop the music on hold so we can play our own file */
2241         if (ringing)
2242                 ast_indicate(qe->chan,-1);
2243         else
2244                 ast_moh_stop(qe->chan);
2245
2246         ast_verb(3, "Playing periodic announcement\n");
2247
2248         /* Check to make sure we have a sound file. If not, reset to the first sound file */
2249         if (qe->last_periodic_announce_sound >= MAX_PERIODIC_ANNOUNCEMENTS || 
2250                 !qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound] ||
2251                 ast_strlen_zero(qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]->str)) {
2252                 qe->last_periodic_announce_sound = 0;
2253         }
2254         
2255         /* play the announcement */
2256         res = play_file(qe->chan, qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]->str);
2257
2258         if ((res > 0 && !valid_exit(qe, res)) || res < 0)
2259                 res = 0;
2260
2261         /* Resume Music on Hold if the caller is going to stay in the queue */
2262         if (!res) {
2263                 if (ringing)
2264                         ast_indicate(qe->chan, AST_CONTROL_RINGING);
2265                 else
2266                         ast_moh_start(qe->chan, qe->moh, NULL);
2267         }
2268
2269         /* update last_periodic_announce_time */
2270         qe->last_periodic_announce_time = now;
2271
2272         /* Update the current periodic announcement to the next announcement */
2273         qe->last_periodic_announce_sound++;
2274         
2275         return res;
2276 }
2277
2278 static void record_abandoned(struct queue_ent *qe)
2279 {
2280         ao2_lock(qe->parent);
2281         set_queue_variables(qe);
2282         manager_event(EVENT_FLAG_AGENT, "QueueCallerAbandon",
2283                 "Queue: %s\r\n"
2284                 "Uniqueid: %s\r\n"
2285                 "Position: %d\r\n"
2286                 "OriginalPosition: %d\r\n"
2287                 "HoldTime: %d\r\n",
2288                 qe->parent->name, qe->chan->uniqueid, qe->pos, qe->opos, (int)(time(NULL) - qe->start));
2289
2290         qe->parent->callsabandoned++;
2291         ao2_unlock(qe->parent);
2292 }
2293
2294 /*! \brief RNA == Ring No Answer. Common code that is executed when we try a queue member and they don't answer. */
2295 static void rna(int rnatime, struct queue_ent *qe, char *interface, char *membername)
2296 {
2297         ast_verb(3, "Nobody picked up in %d ms\n", rnatime);
2298         ast_queue_log(qe->parent->name, qe->chan->uniqueid, membername, "RINGNOANSWER", "%d", rnatime);
2299         if (qe->parent->autopause) {
2300                 if (!set_member_paused(qe->parent->name, interface, "Auto-Pause", 1)) {
2301                         ast_verb(3, "Auto-Pausing Queue Member %s in queue %s since they failed to answer.\n", interface, qe->parent->name);
2302                 } else {
2303                         ast_verb(3, "Failed to pause Queue Member %s in queue %s!\n", interface, qe->parent->name);
2304                 }
2305         }
2306         return;
2307 }
2308
2309 #define AST_MAX_WATCHERS 256
2310
2311 static struct callattempt *wait_for_answer(struct queue_ent *qe, struct callattempt *outgoing, int *to, char *digit, int prebusies, int caller_disconnect, int forwardsallowed)
2312 {
2313         const char *queue = qe->parent->name;
2314         struct callattempt *o, *start = NULL, *prev = NULL;
2315         int status;
2316         int numbusies = prebusies;
2317         int numnochan = 0;
2318         int stillgoing = 0;
2319         int orig = *to;
2320         struct ast_frame *f;
2321         struct callattempt *peer = NULL;
2322         struct ast_channel *winner;
2323         struct ast_channel *in = qe->chan;
2324         char on[80] = "";
2325         char membername[80] = "";
2326         long starttime = 0;
2327         long endtime = 0;
2328 #ifdef HAVE_EPOLL
2329         struct callattempt *epollo;
2330 #endif
2331
2332         starttime = (long) time(NULL);
2333 #ifdef HAVE_EPOLL
2334         for (epollo = outgoing; epollo; epollo = epollo->q_next) {
2335                 if (epollo->chan)
2336                         ast_poll_channel_add(in, epollo->chan);
2337         }
2338 #endif
2339         
2340         while (*to && !peer) {
2341                 int numlines, retry, pos = 1;
2342                 struct ast_channel *watchers[AST_MAX_WATCHERS];
2343                 watchers[0] = in;
2344                 start = NULL;
2345
2346                 for (retry = 0; retry < 2; retry++) {
2347                         numlines = 0;
2348                         for (o = outgoing; o; o = o->q_next) { /* Keep track of important channels */
2349                                 if (o->stillgoing) {    /* Keep track of important channels */
2350                                         stillgoing = 1;
2351                                         if (o->chan) {
2352                                                 watchers[pos++] = o->chan;
2353                                                 if (!start)
2354                                                         start = o;
2355                                                 else
2356                                                         prev->call_next = o;
2357                                                 prev = o;
2358                                         }
2359                                 }
2360                                 numlines++;
2361                         }
2362                         if (pos > 1 /* found */ || !stillgoing /* nobody listening */ ||
2363                                 (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) /* ring would not be delivered */)
2364                                 break;
2365                         /* On "ringall" strategy we only move to the next penalty level
2366                            when *all* ringing phones are done in the current penalty level */
2367                         ring_one(qe, outgoing, &numbusies);
2368                         /* and retry... */
2369                 }
2370                 if (pos == 1 /* not found */) {
2371                         if (numlines == (numbusies + numnochan)) {
2372                                 ast_debug(1, "Everyone is busy at this time\n");
2373                         } else {
2374                                 ast_log(LOG_NOTICE, "No one is answering queue '%s' (%d/%d/%d)\n", queue, numlines, numbusies, numnochan);
2375                         }
2376                         *to = 0;
2377                         return NULL;
2378                 }
2379                 winner = ast_waitfor_n(watchers, pos, to);
2380                 for (o = start; o; o = o->call_next) {
2381                         if (o->stillgoing && (o->chan) &&  (o->chan->_state == AST_STATE_UP)) {
2382                                 if (!peer) {
2383                                         ast_verb(3, "%s answered %s\n", o->chan->name, in->name);
2384                                         peer = o;
2385                                 }
2386                         } else if (o->chan && (o->chan == winner)) {
2387
2388                                 ast_copy_string(on, o->member->interface, sizeof(on));
2389                                 ast_copy_string(membername, o->member->membername, sizeof(membername));
2390
2391                                 if (!ast_strlen_zero(o->chan->call_forward) && !forwardsallowed) {
2392                                         ast_verb(3, "Forwarding %s to '%s' prevented.\n", in->name, o->chan->call_forward);
2393                                         numnochan++;
2394                                         do_hang(o);
2395                                         winner = NULL;
2396                                         continue;
2397                                 } else if (!ast_strlen_zero(o->chan->call_forward)) {
2398                                         char tmpchan[256];
2399                                         char *stuff;
2400                                         char *tech;
2401
2402                                         ast_copy_string(tmpchan, o->chan->call_forward, sizeof(tmpchan));
2403                                         if ((stuff = strchr(tmpchan, '/'))) {
2404                                                 *stuff++ = '\0';
2405                                                 tech = tmpchan;
2406                                         } else {
2407                                                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", o->chan->call_forward, o->chan->context);
2408                                                 stuff = tmpchan;
2409                                                 tech = "Local";
2410                                         }
2411                                         /* Before processing channel, go ahead and check for forwarding */
2412                                         ast_verb(3, "Now forwarding %s to '%s/%s' (thanks to %s)\n", in->name, tech, stuff, o->chan->name);
2413                                         /* Setup parameters */
2414                                         o->chan = ast_request(tech, in->nativeformats, stuff, &status);
2415                                         if (status != o->oldstatus)
2416                                                 update_dial_status(qe->parent, o->member, status);                                              
2417                                         if (!o->chan) {
2418                                                 ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s'\n", tech, stuff);
2419                                                 o->stillgoing = 0;
2420                                                 numnochan++;
2421                                         } else {
2422                                                 ast_channel_inherit_variables(in, o->chan);
2423                                                 ast_channel_datastore_inherit(in, o->chan);
2424                                                 if (o->chan->cid.cid_num)
2425                                                         ast_free(o->chan->cid.cid_num);
2426                                                 o->chan->cid.cid_num = ast_strdup(in->cid.cid_num);
2427
2428                                                 if (o->chan->cid.cid_name)
2429                                                         ast_free(o->chan->cid.cid_name);
2430                                                 o->chan->cid.cid_name = ast_strdup(in->cid.cid_name);
2431
2432                                                 ast_string_field_set(o->chan, accountcode, in->accountcode);
2433                                                 o->chan->cdrflags = in->cdrflags;
2434
2435                                                 if (in->cid.cid_ani) {
2436                                                         if (o->chan->cid.cid_ani)
2437                                                                 ast_free(o->chan->cid.cid_ani);
2438                                                         o->chan->cid.cid_ani = ast_strdup(in->cid.cid_ani);
2439                                                 }
2440                                                 if (o->chan->cid.cid_rdnis)
2441                                                         ast_free(o->chan->cid.cid_rdnis);
2442                                                 o->chan->cid.cid_rdnis = ast_strdup(S_OR(in->macroexten, in->exten));
2443                                                 if (ast_call(o->chan, tmpchan, 0)) {
2444                                                         ast_log(LOG_NOTICE, "Failed to dial on local channel for call forward to '%s'\n", tmpchan);
2445                                                         do_hang(o);
2446                                                         numnochan++;
2447                                                 }
2448                                         }
2449                                         /* Hangup the original channel now, in case we needed it */
2450                                         ast_hangup(winner);
2451                                         continue;
2452                                 }
2453                                 f = ast_read(winner);
2454                                 if (f) {
2455                                         if (f->frametype == AST_FRAME_CONTROL) {
2456                                                 switch (f->subclass) {
2457                                                 case AST_CONTROL_ANSWER:
2458                                                         /* This is our guy if someone answered. */
2459                                                         if (!peer) {
2460                                                                 ast_verb(3, "%s answered %s\n", o->chan->name, in->name);
2461                                                                 peer = o;
2462                                                         }
2463                                                         break;
2464                                                 case AST_CONTROL_BUSY:
2465                                                         ast_verb(3, "%s is busy\n", o->chan->name);
2466                                                         if (in->cdr)
2467                                                                 ast_cdr_busy(in->cdr);
2468                                                         do_hang(o);
2469                                                         endtime = (long) time(NULL);
2470                                                         endtime -= starttime;
2471                                                         rna(endtime*1000, qe, on, membername);
2472                                                         if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
2473                                                                 if (qe->parent->timeoutrestart)
2474                                                                         *to = orig;
2475                                                                 ring_one(qe, outgoing, &numbusies);
2476                                                         }
2477                                                         numbusies++;
2478                                                         break;
2479                                                 case AST_CONTROL_CONGESTION:
2480                                                         ast_verb(3, "%s is circuit-busy\n", o->chan->name);
2481                                                         if (in->cdr)
2482                                                                 ast_cdr_busy(in->cdr);
2483                                                         endtime = (long) time(NULL);
2484                                                         endtime -= starttime;
2485                                                         rna(endtime*1000, qe, on, membername);
2486                                                         do_hang(o);
2487                                                         if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
2488                                                                 if (qe->parent->timeoutrestart)
2489                                                                         *to = orig;
2490                                                                 ring_one(qe, outgoing, &numbusies);
2491                                                         }
2492                                                         numbusies++;
2493                                                         break;
2494                                                 case AST_CONTROL_RINGING:
2495                                                         ast_verb(3, "%s is ringing\n", o->chan->name);
2496                                                         break;
2497                                                 case AST_CONTROL_OFFHOOK:
2498                                                         /* Ignore going off hook */
2499                                                         break;
2500                                                 default:
2501                                                         ast_debug(1, "Dunno what to do with control type %d\n", f->subclass);
2502                                                 }
2503                                         }
2504                                         ast_frfree(f);
2505                                 } else {
2506                                         endtime = (long) time(NULL) - starttime;
2507                                         rna(endtime * 1000, qe, on, membername);
2508                                         do_hang(o);
2509                                         if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
2510                                                 if (qe->parent->timeoutrestart)
2511                                                         *to = orig;
2512                                                 ring_one(qe, outgoing, &numbusies);
2513                                         }
2514                                 }
2515                         }
2516                 }
2517                 if (winner == in) {
2518                         f = ast_read(in);
2519                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))) {
2520                                 /* Got hung up */
2521                                 *to = -1;
2522                                 if (f) {
2523                                         ast_frfree(f);
2524                                 }
2525                                 return NULL;
2526                         }
2527                         if ((f->frametype == AST_FRAME_DTMF) && caller_disconnect && (f->subclass == '*')) {
2528                                 ast_verb(3, "User hit %c to disconnect call.\n", f->subclass);
2529                                 *to = 0;
2530                                 ast_frfree(f);
2531                                 return NULL;
2532                         }
2533                         if ((f->frametype == AST_FRAME_DTMF) && valid_exit(qe, f->subclass)) {
2534                                 ast_verb(3, "User pressed digit: %c\n", f->subclass);
2535                                 *to = 0;
2536                                 *digit = f->subclass;
2537                                 ast_frfree(f);
2538                                 return NULL;
2539                         }
2540                         ast_frfree(f);
2541                 }
2542                 if (!*to) {
2543                         for (o = start; o; o = o->call_next)
2544                                 rna(orig, qe, o->interface, o->member->membername);
2545                 }
2546         }
2547
2548 #ifdef HAVE_EPOLL
2549         for (epollo = outgoing; epollo; epollo = epollo->q_next) {
2550                 if (epollo->chan)
2551                         ast_poll_channel_del(in, epollo->chan);
2552         }
2553 #endif
2554
2555         return peer;
2556 }
2557
2558 static int is_our_turn(struct queue_ent *qe)
2559 {
2560         struct queue_ent *ch;
2561         struct member *cur;
2562         int avl = 0;
2563         int idx = 0;
2564         int res;
2565
2566         if (!qe->parent->autofill) {
2567                 /* Atomically read the parent head -- does not need a lock */
2568                 ch = qe->parent->head;
2569                 /* If we are now at the top of the head, break out */
2570                 if (ch == qe) {
2571                         ast_debug(1, "It's our turn (%s).\n", qe->chan->name);
2572                         res = 1;
2573                 } else {
2574                         ast_debug(1, "It's not our turn (%s).\n", qe->chan->name);
2575                         res = 0;
2576                 }       
2577
2578         } else {
2579                 /* This needs a lock. How many members are available to be served? */
2580                 ao2_lock(qe->parent);
2581                         
2582                 ch = qe->parent->head;
2583         
2584                 if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
2585                         ast_debug(1, "Even though there may be multiple members available, the strategy is ringall so only the head call is allowed in\n");
2586                         avl = 1;
2587                 } else {
2588                         struct ao2_iterator mem_iter = ao2_iterator_init(qe->parent->members, 0);
2589                         while ((cur = ao2_iterator_next(&mem_iter))) {
2590                                 switch (cur->status) {
2591                                 case AST_DEVICE_NOT_INUSE:
2592                                 case AST_DEVICE_UNKNOWN:
2593                                         if (!cur->paused)
2594                                                 avl++;
2595                                         break;
2596                                 }
2597                                 ao2_ref(cur, -1);
2598                         }
2599                 }
2600
2601                 ast_debug(1, "There are %d available members.\n", avl);
2602         
2603                 while ((idx < avl) && (ch) &&  !ch->pending && (ch != qe)) {
2604                         idx++;
2605                         ch = ch->next;                  
2606                 }
2607         
2608                 /* If the queue entry is within avl [the number of available members] calls from the top ... */
2609                 if (ch && idx < avl) {
2610                         ast_debug(1, "It's our turn (%s).\n", qe->chan->name);
2611                         res = 1;
2612                 } else {
2613                         ast_debug(1, "It's not our turn (%s).\n", qe->chan->name);
2614                         res = 0;
2615                 }
2616                 
2617                 ao2_unlock(qe->parent);
2618         }
2619
2620         return res;
2621 }
2622
2623 static void update_qe_rule(struct queue_ent *qe)
2624 {
2625         int max_penalty = qe->pr->max_relative ? qe->max_penalty + qe->pr->max_value : qe->pr->max_value;
2626         int min_penalty = qe->pr->min_relative ? qe->min_penalty + qe->pr->min_value : qe->pr->min_value;
2627         char max_penalty_str[20], min_penalty_str[20]; 
2628         /* a relative change to the penalty could put it below 0 */
2629         if (max_penalty < 0)
2630                 max_penalty = 0;
2631         if (min_penalty < 0)
2632                 min_penalty = 0;
2633         if (min_penalty > max_penalty)
2634                 min_penalty = max_penalty;
2635         snprintf(max_penalty_str, sizeof(max_penalty_str) - 1, "%d", max_penalty);
2636         snprintf(min_penalty_str, sizeof(min_penalty_str) - 1, "%d", min_penalty);
2637         pbx_builtin_setvar_helper(qe->chan, "QUEUE_MAX_PENALTY", max_penalty_str);
2638         pbx_builtin_setvar_helper(qe->chan, "QUEUE_MIN_PENALTY", min_penalty_str);
2639         qe->max_penalty = max_penalty;
2640         qe->min_penalty = min_penalty;
2641         ast_debug(3, "Setting max penalty to %d and min penalty to %d for caller %s since %d seconds have elapsed\n", qe->max_penalty, qe->min_penalty, qe->chan->name, qe->pr->time);
2642         qe->pr = AST_LIST_NEXT(qe->pr, list);
2643 }
2644
2645 static int wait_our_turn(struct queue_ent *qe, int ringing, enum queue_result *reason)
2646 {
2647         int res = 0;
2648
2649         /* This is the holding pen for callers 2 through maxlen */
2650         for (;;) {
2651                 enum queue_member_status stat;
2652
2653                 if (is_our_turn(qe))
2654                         break;
2655
2656                 /* If we have timed out, break out */
2657                 if (qe->expire && (time(NULL) > qe->expire)) {
2658                         *reason = QUEUE_TIMEOUT;
2659                         break;
2660                 }
2661
2662                 stat = get_member_status(qe->parent, qe->max_penalty, qe->min_penalty);
2663
2664                 /* leave the queue if no agents, if enabled */
2665                 if (qe->parent->leavewhenempty && (stat == QUEUE_NO_MEMBERS)) {
2666                         *reason = QUEUE_LEAVEEMPTY;
2667                         ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2668                         leave_queue(qe);
2669                         break;
2670                 }
2671
2672                 /* leave the queue if no reachable agents, if enabled */
2673                 if ((qe->parent->leavewhenempty == QUEUE_EMPTY_STRICT) && (stat == QUEUE_NO_REACHABLE_MEMBERS || stat == QUEUE_NO_UNPAUSED_REACHABLE_MEMBERS)) {
2674                         *reason = QUEUE_LEAVEUNAVAIL;
2675                         ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2676                         leave_queue(qe);
2677                         break;
2678                 }
2679                 if ((qe->parent->leavewhenempty == QUEUE_EMPTY_LOOSE) && (stat == QUEUE_NO_REACHABLE_MEMBERS)) {
2680                         *reason = QUEUE_LEAVEUNAVAIL;
2681                         ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2682                         leave_queue(qe);
2683                         break;
2684                 }
2685
2686                 /* Make a position announcement, if enabled */
2687                 if (qe->parent->announcefrequency &&
2688                         (res = say_position(qe,ringing)))
2689                         break;
2690
2691                 /* Make a periodic announcement, if enabled */
2692                 if (qe->parent->periodicannouncefrequency &&
2693                         (res = say_periodic_announcement(qe,ringing)))
2694                         break;
2695                 
2696                 /* see if we need to move to the next penalty level for this queue */
2697                 while (qe->pr && ((time(NULL) - qe->start) > qe->pr->time)) {
2698                         update_qe_rule(qe);
2699                 }
2700
2701                 /* Wait a second before checking again */
2702                 if ((res = ast_waitfordigit(qe->chan, RECHECK * 1000))) {
2703                         if (res > 0 && !valid_exit(qe, res))
2704                                 res = 0;
2705                         else
2706                                 break;
2707                 }
2708         }
2709
2710         return res;
2711 }
2712
2713 static int update_queue(struct call_queue *q, struct member *member, int callcompletedinsl)
2714 {
2715         struct member *mem;
2716         struct call_queue *qtmp;
2717         struct ao2_iterator queue_iter; 
2718         
2719         if (shared_lastcall) {
2720                 queue_iter = ao2_iterator_init(queues, 0);
2721                 while ((qtmp = ao2_iterator_next(&queue_iter))) {
2722                         ao2_lock(qtmp);
2723                         if ((mem = ao2_find(qtmp->members, member, OBJ_POINTER))) {
2724                                 time(&mem->lastcall);
2725                                 mem->calls++;
2726                                 mem->lastqueue = q;
2727                                 ao2_ref(mem, -1);
2728                         }
2729                         ao2_unlock(qtmp);
2730                         ao2_ref(qtmp, -1);
2731                 }
2732         } else {
2733                 ao2_lock(q);
2734                 time(&member->lastcall);
2735                 member->calls++;
2736                 member->lastqueue = q;
2737                 ao2_unlock(q);
2738         }       
2739         ao2_lock(q);
2740         q->callscompleted++;
2741         if (callcompletedinsl)
2742                 q->callscompletedinsl++;
2743         ao2_unlock(q);
2744         return 0;
2745 }
2746
2747 static int calc_metric(struct call_queue *q, struct member *mem, int pos, struct queue_ent *qe, struct callattempt *tmp)
2748 {
2749         if ((qe->max_penalty && (mem->penalty > qe->max_penalty)) || (qe->min_penalty && (mem->penalty < qe->min_penalty)))
2750                 return -1;
2751
2752         switch (q->strategy) {
2753         case QUEUE_STRATEGY_RINGALL:
2754                 /* Everyone equal, except for penalty */
2755                 tmp->metric = mem->penalty * 1000000;
2756                 break;
2757         case QUEUE_STRATEGY_LINEAR:
2758                 if (pos < qe->linpos) {
2759                         tmp->metric = 1000 + pos;
2760                 } else {
2761                         if (pos > qe->linpos)
2762                                 /* Indicate there is another priority */
2763                                 qe->linwrapped = 1;
2764                         tmp->metric = pos;
2765                 }
2766                 tmp->metric += mem->penalty * 1000000;
2767                 break;
2768         case QUEUE_STRATEGY_RRMEMORY:
2769                 if (pos < q->rrpos) {
2770                         tmp->metric = 1000 + pos;
2771                 } else {
2772                         if (pos > q->rrpos)
2773                                 /* Indicate there is another priority */
2774                                 q->wrapped = 1;
2775                         tmp->metric = pos;
2776                 }
2777                 tmp->metric += mem->penalty * 1000000;
2778                 break;
2779         case QUEUE_STRATEGY_RANDOM:
2780                 tmp->metric = ast_random() % 1000;
2781                 tmp->metric += mem->penalty * 1000000;
2782                 break;
2783         case QUEUE_STRATEGY_WRANDOM:
2784                 tmp->metric = ast_random() % ((1 + mem->penalty) * 1000);
2785                 break;
2786         case QUEUE_STRATEGY_FEWESTCALLS:
2787                 tmp->metric = mem->calls;
2788                 tmp->metric += mem->penalty * 1000000;
2789                 break;
2790         case QUEUE_STRATEGY_LEASTRECENT:
2791                 if (!mem->lastcall)
2792                         tmp->metric = 0;
2793                 else
2794                         tmp->metric = 1000000 - (time(NULL) - mem->lastcall);
2795                 tmp->metric += mem->penalty * 1000000;
2796                 break;
2797         default:
2798                 ast_log(LOG_WARNING, "Can't calculate metric for unknown strategy %d\n", q->strategy);
2799                 break;
2800         }
2801         return 0;
2802 }
2803
2804 enum agent_complete_reason {
2805         CALLER,
2806         AGENT,
2807         TRANSFER
2808 };
2809
2810 static void send_agent_complete(const struct queue_ent *qe, const char *queuename,
2811         const struct ast_channel *peer, const struct member *member, time_t callstart,
2812         char *vars, size_t vars_len, enum agent_complete_reason rsn)
2813 {
2814         const char *reason = NULL;      /* silence dumb compilers */
2815
2816         if (!qe->parent->eventwhencalled)
2817                 return;
2818
2819         switch (rsn) {
2820         case CALLER:
2821                 reason = "caller";
2822                 break;
2823         case AGENT:
2824                 reason = "agent";
2825                 break;
2826         case TRANSFER:
2827                 reason = "transfer";
2828                 break;
2829         }
2830
2831         manager_event(EVENT_FLAG_AGENT, "AgentComplete",
2832                 "Queue: %s\r\n"
2833                 "Uniqueid: %s\r\n"
2834                 "Channel: %s\r\n"
2835                 "Member: %s\r\n"
2836                 "MemberName: %s\r\n"
2837                 "HoldTime: %ld\r\n"
2838                 "TalkTime: %ld\r\n"
2839                 "Reason: %s\r\n"
2840                 "%s",
2841                 queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
2842                 (long)(callstart - qe->start), (long)(time(NULL) - callstart), reason,
2843                 qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, vars_len) : "");
2844 }
2845
2846 static int try_calling(struct queue_ent *qe, const char *options, char *announceoverride, const char *url, int *tries, int *noption, const char *agi, const char *macro, const char *gosub, int ringing)
2847 {
2848         struct member *cur;
2849         struct callattempt *outgoing = NULL; /* the list of calls we are building */
2850         int to, orig;
2851         char oldexten[AST_MAX_EXTENSION]="";
2852         char oldcontext[AST_MAX_CONTEXT]="";
2853         char queuename[256]="";
2854         char interfacevar[256]="";
2855         struct ast_channel *peer;
2856         struct ast_channel *which;
2857         struct callattempt *lpeer;
2858         struct member *member;
2859         struct ast_app *app;
2860         int res = 0, bridge = 0;
2861         int numbusies = 0;
2862         int x=0;
2863         char *announce = NULL;
2864         char digit = 0;
2865         time_t callstart;
2866         time_t now = time(NULL);
2867         struct ast_bridge_config bridge_config;
2868         char nondataquality = 1;
2869         char *agiexec = NULL;
2870         char *macroexec = NULL;
2871         char *gosubexec = NULL;
2872         int ret = 0;
2873         const char *monitorfilename;
2874         const char *monitor_exec;
2875         const char *monitor_options;
2876         char tmpid[256], tmpid2[256];
2877         char meid[1024], meid2[1024];
2878         char mixmonargs[1512];
2879         struct ast_app *mixmonapp = NULL;
2880         char *p;
2881         char vars[2048];
2882         int forwardsallowed = 1;
2883         int callcompletedinsl;
2884         struct ao2_iterator memi;
2885         struct ast_datastore *datastore;
2886
2887         ast_channel_lock(qe->chan);
2888         datastore = ast_channel_datastore_find(qe->chan, &dialed_interface_info, NULL);
2889         ast_channel_unlock(qe->chan);
2890
2891         memset(&bridge_config, 0, sizeof(bridge_config));
2892         tmpid[0] = 0;
2893         meid[0] = 0;
2894         time(&now);
2895                 
2896         for (; options && *options; options++)
2897                 switch (*options) {
2898                 case 't':
2899                         ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_REDIRECT);
2900                         break;
2901                 case 'T':
2902                         ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_REDIRECT);
2903                         break;
2904                 case 'w':
2905                         ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_AUTOMON);
2906                         break;
2907                 case 'W':
2908                         ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_AUTOMON);
2909                         break;
2910                 case 'd':
2911                         nondataquality = 0;
2912                         break;
2913                 case 'h':
2914                         ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_DISCONNECT);
2915                         break;
2916                 case 'H':
2917                         ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_DISCONNECT);
2918                         break;
2919                 case 'k':
2920                         ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_PARKCALL);
2921                         break;
2922                 case 'K':
2923                         ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_PARKCALL);
2924                         break;
2925                 case 'n':
2926                         if (qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY || qe->parent->strategy == QUEUE_STRATEGY_LINEAR)
2927                                 (*tries)++;
2928                         else
2929                                 *tries = qe->parent->membercount;
2930                         *noption = 1;
2931                         break;
2932                 case 'i':
2933                         forwardsallowed = 0;
2934                         break;
2935                 case 'x':
2936                         ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_AUTOMIXMON);
2937                         break;
2938                 case 'X':
2939                         ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_AUTOMIXMON);
2940                         break;
2941
2942                 }
2943
2944         /* Hold the lock while we setup the outgoing calls */
2945         if (use_weight)
2946                 ao2_lock(queues);
2947         ao2_lock(qe->parent);
2948         ast_debug(1, "%s is trying to call a queue member.\n",
2949                                                         qe->chan->name);
2950         ast_copy_string(queuename, qe->parent->name, sizeof(queuename));
2951         if (!ast_strlen_zero(qe->announce))
2952                 announce = qe->announce;
2953         if (!ast_strlen_zero(announceoverride))
2954                 announce = announceoverride;
2955
2956         memi = ao2_iterator_init(qe->parent->members, 0);
2957         while ((cur = ao2_iterator_next(&memi))) {
2958                 struct callattempt *tmp = ast_calloc(1, sizeof(*tmp));
2959                 struct ast_dialed_interface *di;
2960                 AST_LIST_HEAD(, ast_dialed_interface) *dialed_interfaces;
2961                 if (!tmp) {
2962                         ao2_ref(cur, -1);
2963                         ao2_unlock(qe->parent);
2964                         if (use_weight)
2965                                 ao2_unlock(queues);
2966                         goto out;
2967                 }
2968                 if (!datastore) {
2969                         if (!(datastore = ast_channel_datastore_alloc(&dialed_interface_info, NULL))) {
2970                                 ao2_ref(cur, -1);
2971                                 ao2_unlock(qe->parent);
2972                                 if (use_weight)
2973                                         ao2_unlock(queues);
2974                                 free(tmp);
2975                                 goto out;
2976                         }
2977                         datastore->inheritance = DATASTORE_INHERIT_FOREVER;
2978                         if (!(dialed_interfaces = ast_calloc(1, sizeof(*dialed_interfaces)))) {
2979                                 ao2_ref(cur, -1);
2980                                 ao2_unlock(&qe->parent);
2981                                 if (use_weight)
2982                                         ao2_unlock(queues);
2983                                 free(tmp);
2984                                 goto out;
2985                         }
2986                         datastore->data = dialed_interfaces;
2987                         AST_LIST_HEAD_INIT(dialed_interfaces);
2988
2989                         ast_channel_lock(qe->chan);
2990                         ast_channel_datastore_add(qe->chan, datastore);
2991                         ast_channel_unlock(qe->chan);
2992                 } else
2993                         dialed_interfaces = datastore->data;
2994
2995                 AST_LIST_LOCK(dialed_interfaces);
2996                 AST_LIST_TRAVERSE(dialed_interfaces, di, list) {
2997                         if (!strcasecmp(cur->interface, di->interface)) {
2998                                 ast_log(LOG_DEBUG, "Skipping dialing interface '%s' since it has already been dialed\n", 
2999                                         di->interface);
3000                                 break;
3001                         }
3002                 }
3003                 AST_LIST_UNLOCK(dialed_interfaces);
3004                 
3005                 if (di) {
3006                         free(tmp);
3007                         continue;
3008                 }
3009
3010                 /* It is always ok to dial a Local interface.  We only keep track of
3011                  * which "real" interfaces have been dialed.  The Local channel will
3012