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