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