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