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