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