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