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