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