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