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