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