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