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