Merged revisions 83074 via svnmerge from
[asterisk/asterisk.git] / apps / app_queue.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief True call queues with optional send URL on answer
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * \arg Config in \ref Config_qu queues.conf
26  *
27  * \par Development notes
28  * \note 2004-11-25: Persistent Dynamic Members added by:
29  *             NetNation Communications (www.netnation.com)
30  *             Kevin Lindsay <kevinl@netnation.com>
31  *
32  *             Each dynamic agent in each queue is now stored in the astdb.
33  *             When asterisk is restarted, each agent will be automatically
34  *             readded into their recorded queues. This feature can be
35  *             configured with the 'persistent_members=<1|0>' setting in the
36  *             '[general]' category in queues.conf. The default is on.
37  *
38  * \note 2004-06-04: Priorities in queues added by inAccess Networks (work funded by Hellas On Line (HOL) www.hol.gr).
39  *
40  * \note These features added by David C. Troy <dave@toad.net>:
41  *    - Per-queue holdtime calculation
42  *    - Estimated holdtime announcement
43  *    - Position announcement
44  *    - Abandoned/completed call counters
45  *    - Failout timer passed as optional app parameter
46  *    - Optional monitoring of calls, started when call is answered
47  *
48  * Patch Version 1.07 2003-12-24 01
49  *
50  * Added servicelevel statistic by Michiel Betel <michiel@betel.nl>
51  * Added Priority jumping code for adding and removing queue members by Jonathan Stanton <asterisk@doilooklikeicare.com>
52  *
53  * Fixed to work with CVS as of 2004-02-25 and released as 1.07a
54  * by Matthew Enger <m.enger@xi.com.au>
55  *
56  * \ingroup applications
57  */
58
59 #include "asterisk.h"
60
61 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
62
63 #include <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                 if(!ast_strlen_zero(membername))
726                         ast_copy_string(cur->membername, membername, sizeof(cur->membername));
727                 else
728                         ast_copy_string(cur->membername, interface, sizeof(cur->membername));
729                 if (!strchr(cur->interface, '/'))
730                         ast_log(LOG_WARNING, "No location at interface '%s'\n", interface);
731                 cur->status = ast_device_state(interface);
732         }
733
734         return cur;
735 }
736
737 static struct call_queue *alloc_queue(const char *queuename)
738 {
739         struct call_queue *q;
740
741         if ((q = ast_calloc(1, sizeof(*q)))) {
742                 ast_mutex_init(&q->lock);
743                 ast_copy_string(q->name, queuename, sizeof(q->name));
744         }
745         return q;
746 }
747
748 static int compress_char(const char c)
749 {
750         if (c < 32)
751                 return 0;
752         else if (c > 96)
753                 return c - 64;
754         else
755                 return c - 32;
756 }
757
758 static int member_hash_fn(const void *obj, const int flags)
759 {
760         const struct member *mem = obj;
761         const char *chname = strchr(mem->interface, '/');
762         int ret = 0, i;
763         if (!chname)
764                 chname = mem->interface;
765         for (i = 0; i < 5 && chname[i]; i++)
766                 ret += compress_char(chname[i]) << (i * 6);
767         return ret;
768 }
769
770 static int member_cmp_fn(void *obj1, void *obj2, int flags)
771 {
772         struct member *mem1 = obj1, *mem2 = obj2;
773         return strcmp(mem1->interface, mem2->interface) ? 0 : CMP_MATCH;
774 }
775
776 static void init_queue(struct call_queue *q)
777 {
778         int i;
779
780         q->dead = 0;
781         q->retry = DEFAULT_RETRY;
782         q->timeout = -1;
783         q->maxlen = 0;
784         q->announcefrequency = 0;
785         q->minannouncefrequency = DEFAULT_MIN_ANNOUNCE_FREQUENCY;
786         q->announceholdtime = 0;
787         q->roundingseconds = 0; /* Default - don't announce seconds */
788         q->servicelevel = 0;
789         q->ringinuse = 1;
790         q->setinterfacevar = 0;
791         q->setqueuevar = 0;
792         q->setqueueentryvar = 0;
793         q->autofill = autofill_default;
794         q->montype = montype_default;
795         q->membermacro[0] = '\0';
796         q->membergosub[0] = '\0';
797         q->moh[0] = '\0';
798         q->announce[0] = '\0';
799         q->context[0] = '\0';
800         q->monfmt[0] = '\0';
801         q->periodicannouncefrequency = 0;
802         q->sound_callerannounce[0] = '\0';      /* Default, don't announce the caller that he has been answered */
803         q->members = ao2_container_alloc(37, member_hash_fn, member_cmp_fn);
804         q->membercount = 0;
805         q->found = 1;
806         ast_copy_string(q->sound_next, "queue-youarenext", sizeof(q->sound_next));
807         ast_copy_string(q->sound_thereare, "queue-thereare", sizeof(q->sound_thereare));
808         ast_copy_string(q->sound_calls, "queue-callswaiting", sizeof(q->sound_calls));
809         ast_copy_string(q->sound_holdtime, "queue-holdtime", sizeof(q->sound_holdtime));
810         ast_copy_string(q->sound_minutes, "queue-minutes", sizeof(q->sound_minutes));
811         ast_copy_string(q->sound_seconds, "queue-seconds", sizeof(q->sound_seconds));
812         ast_copy_string(q->sound_thanks, "queue-thankyou", sizeof(q->sound_thanks));
813         ast_copy_string(q->sound_lessthan, "queue-less-than", sizeof(q->sound_lessthan));
814         ast_copy_string(q->sound_reporthold, "queue-reporthold", sizeof(q->sound_reporthold));
815         ast_copy_string(q->sound_periodicannounce[0], "queue-periodic-announce", sizeof(q->sound_periodicannounce[0]));
816         for (i = 1; i < MAX_PERIODIC_ANNOUNCEMENTS; i++) {
817                 q->sound_periodicannounce[i][0]='\0';
818         }
819 }
820
821 static void clear_queue(struct call_queue *q)
822 {
823         q->holdtime = 0;
824         q->callscompleted = 0;
825         q->callsabandoned = 0;
826         q->callscompletedinsl = 0;
827         q->wrapuptime = 0;
828 }
829
830 static int add_to_interfaces(const char *interface)
831 {
832         struct member_interface *curint;
833
834         AST_LIST_LOCK(&interfaces);
835         AST_LIST_TRAVERSE(&interfaces, curint, list) {
836                 if (!strcasecmp(curint->interface, interface))
837                         break;
838         }
839
840         if (curint) {
841                 AST_LIST_UNLOCK(&interfaces);
842                 return 0;
843         }
844
845         ast_debug(1, "Adding %s to the list of interfaces that make up all of our queue members.\n", interface);
846         
847         if ((curint = ast_calloc(1, sizeof(*curint)))) {
848                 ast_copy_string(curint->interface, interface, sizeof(curint->interface));
849                 AST_LIST_INSERT_HEAD(&interfaces, curint, list);
850         }
851         AST_LIST_UNLOCK(&interfaces);
852
853         return 0;
854 }
855
856 static int interface_exists_global(const char *interface)
857 {
858         struct call_queue *q;
859         struct member *mem, tmpmem;
860         int ret = 0;
861
862         ast_copy_string(tmpmem.interface, interface, sizeof(tmpmem.interface));
863
864         AST_LIST_LOCK(&queues);
865         AST_LIST_TRAVERSE(&queues, q, list) {
866                 ast_mutex_lock(&q->lock);
867                 if ((mem = ao2_find(q->members, &tmpmem, OBJ_POINTER))) {
868                         ao2_ref(mem, -1);
869                         ret = 1;
870                 }
871                 ast_mutex_unlock(&q->lock);
872                 if (ret)
873                         break;
874         }
875         AST_LIST_UNLOCK(&queues);
876
877         return ret;
878 }
879
880 static int remove_from_interfaces(const char *interface)
881 {
882         struct member_interface *curint;
883
884         AST_LIST_LOCK(&interfaces);
885         AST_LIST_TRAVERSE_SAFE_BEGIN(&interfaces, curint, list) {
886                 if (!strcasecmp(curint->interface, interface)) {
887                         if (!interface_exists_global(interface)) {
888                                 ast_debug(1, "Removing %s from the list of interfaces that make up all of our queue members.\n", interface);
889                                 AST_LIST_REMOVE_CURRENT(&interfaces, list);
890                                 ast_free(curint);
891                         }
892                         break;
893                 }
894         }
895         AST_LIST_TRAVERSE_SAFE_END;
896         AST_LIST_UNLOCK(&interfaces);
897
898         return 0;
899 }
900
901 static void clear_and_free_interfaces(void)
902 {
903         struct member_interface *curint;
904
905         AST_LIST_LOCK(&interfaces);
906         while ((curint = AST_LIST_REMOVE_HEAD(&interfaces, list)))
907                 ast_free(curint);
908         AST_LIST_UNLOCK(&interfaces);
909 }
910
911 /*! \brief Configure a queue parameter.
912 \par
913    For error reporting, line number is passed for .conf static configuration.
914    For Realtime queues, linenum is -1.
915    The failunknown flag is set for config files (and static realtime) to show
916    errors for unknown parameters. It is cleared for dynamic realtime to allow
917    extra fields in the tables. */
918 static void queue_set_param(struct call_queue *q, const char *param, const char *val, int linenum, int failunknown)
919 {
920         if (!strcasecmp(param, "musicclass") || 
921                 !strcasecmp(param, "music") || !strcasecmp(param, "musiconhold")) {
922                 ast_copy_string(q->moh, val, sizeof(q->moh));
923         } else if (!strcasecmp(param, "announce")) {
924                 ast_copy_string(q->announce, val, sizeof(q->announce));
925         } else if (!strcasecmp(param, "context")) {
926                 ast_copy_string(q->context, val, sizeof(q->context));
927         } else if (!strcasecmp(param, "timeout")) {
928                 q->timeout = atoi(val);
929                 if (q->timeout < 0)
930                         q->timeout = DEFAULT_TIMEOUT;
931         } else if (!strcasecmp(param, "ringinuse")) {
932                 q->ringinuse = ast_true(val);
933         } else if (!strcasecmp(param, "setinterfacevar")) {
934                 q->setinterfacevar = ast_true(val);
935         } else if (!strcasecmp(param, "setqueuevar")) {
936                 q->setqueuevar = ast_true(val);
937         } else if (!strcasecmp(param, "setqueueentryvar")) {
938                 q->setqueueentryvar = ast_true(val);
939         } else if (!strcasecmp(param, "monitor-join")) {
940                 q->monjoin = ast_true(val);
941         } else if (!strcasecmp(param, "monitor-format")) {
942                 ast_copy_string(q->monfmt, val, sizeof(q->monfmt));
943         } else if (!strcasecmp(param, "membermacro")) {
944                 ast_copy_string(q->membermacro, val, sizeof(q->membermacro));
945         } else if (!strcasecmp(param, "membergosub")) {
946                 ast_copy_string(q->membergosub, val, sizeof(q->membergosub));
947         } else if (!strcasecmp(param, "queue-youarenext")) {
948                 ast_copy_string(q->sound_next, val, sizeof(q->sound_next));
949         } else if (!strcasecmp(param, "queue-thereare")) {
950                 ast_copy_string(q->sound_thereare, val, sizeof(q->sound_thereare));
951         } else if (!strcasecmp(param, "queue-callswaiting")) {
952                 ast_copy_string(q->sound_calls, val, sizeof(q->sound_calls));
953         } else if (!strcasecmp(param, "queue-holdtime")) {
954                 ast_copy_string(q->sound_holdtime, val, sizeof(q->sound_holdtime));
955         } else if (!strcasecmp(param, "queue-minutes")) {
956                 ast_copy_string(q->sound_minutes, val, sizeof(q->sound_minutes));
957         } else if (!strcasecmp(param, "queue-seconds")) {
958                 ast_copy_string(q->sound_seconds, val, sizeof(q->sound_seconds));
959         } else if (!strcasecmp(param, "queue-lessthan")) {
960                 ast_copy_string(q->sound_lessthan, val, sizeof(q->sound_lessthan));
961         } else if (!strcasecmp(param, "queue-thankyou")) {
962                 ast_copy_string(q->sound_thanks, val, sizeof(q->sound_thanks));
963         } else if (!strcasecmp(param, "queue-callerannounce")) {
964                 ast_copy_string(q->sound_callerannounce, val, sizeof(q->sound_callerannounce));
965         } else if (!strcasecmp(param, "queue-reporthold")) {
966                 ast_copy_string(q->sound_reporthold, val, sizeof(q->sound_reporthold));
967         } else if (!strcasecmp(param, "announce-frequency")) {
968                 q->announcefrequency = atoi(val);
969         } else if (!strcasecmp(param, "min-announce-frequency")) {
970                 q->minannouncefrequency = atoi(val);
971                 ast_debug(1, "%s=%s for queue '%s'\n", param, val, q->name);
972         } else if (!strcasecmp(param, "announce-round-seconds")) {
973                 q->roundingseconds = atoi(val);
974                 /* Rounding to any other values just doesn't make sense... */
975                 if (!(q->roundingseconds == 0 || q->roundingseconds == 1 || q->roundingseconds == 5 || q->roundingseconds == 10
976                         || q->roundingseconds == 15 || q->roundingseconds == 20 || q->roundingseconds == 30)) {
977                         if (linenum >= 0) {
978                                 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
979                                         "using 0 instead for queue '%s' at line %d of queues.conf\n",
980                                         val, param, q->name, linenum);
981                         } else {
982                                 ast_log(LOG_WARNING, "'%s' isn't a valid value for %s "
983                                         "using 0 instead for queue '%s'\n", val, param, q->name);
984                         }
985                         q->roundingseconds=0;
986                 }
987         } else if (!strcasecmp(param, "announce-holdtime")) {
988                 if (!strcasecmp(val, "once"))
989                         q->announceholdtime = ANNOUNCEHOLDTIME_ONCE;
990                 else if (ast_true(val))
991                         q->announceholdtime = ANNOUNCEHOLDTIME_ALWAYS;
992                 else
993                         q->announceholdtime = 0;
994         } else if (!strcasecmp(param, "periodic-announce")) {
995                 if (strchr(val, ',')) {
996                         char *s, *buf = ast_strdupa(val);
997                         unsigned int i = 0;
998
999                         while ((s = strsep(&buf, ",|"))) {
1000                                 ast_copy_string(q->sound_periodicannounce[i], s, sizeof(q->sound_periodicannounce[i]));
1001                                 i++;
1002                                 if (i == MAX_PERIODIC_ANNOUNCEMENTS)
1003                                         break;
1004                         }
1005                 } else {
1006                         ast_copy_string(q->sound_periodicannounce[0], val, sizeof(q->sound_periodicannounce[0]));
1007                 }
1008         } else if (!strcasecmp(param, "periodic-announce-frequency")) {
1009                 q->periodicannouncefrequency = atoi(val);
1010         } else if (!strcasecmp(param, "retry")) {
1011                 q->retry = atoi(val);
1012                 if (q->retry <= 0)
1013                         q->retry = DEFAULT_RETRY;
1014         } else if (!strcasecmp(param, "wrapuptime")) {
1015                 q->wrapuptime = atoi(val);
1016         } else if (!strcasecmp(param, "autofill")) {
1017                 q->autofill = ast_true(val);
1018         } else if (!strcasecmp(param, "monitor-type")) {
1019                 if (!strcasecmp(val, "mixmonitor"))
1020                         q->montype = 1;
1021         } else if (!strcasecmp(param, "autopause")) {
1022                 q->autopause = ast_true(val);
1023         } else if (!strcasecmp(param, "maxlen")) {
1024                 q->maxlen = atoi(val);
1025                 if (q->maxlen < 0)
1026                         q->maxlen = 0;
1027         } else if (!strcasecmp(param, "servicelevel")) {
1028                 q->servicelevel= atoi(val);
1029         } else if (!strcasecmp(param, "strategy")) {
1030                 q->strategy = strat2int(val);
1031                 if (q->strategy < 0) {
1032                         ast_log(LOG_WARNING, "'%s' isn't a valid strategy for queue '%s', using ringall instead\n",
1033                                 val, q->name);
1034                         q->strategy = QUEUE_STRATEGY_RINGALL;
1035                 }
1036         } else if (!strcasecmp(param, "joinempty")) {
1037                 if (!strcasecmp(val, "loose"))
1038                         q->joinempty = QUEUE_EMPTY_LOOSE;
1039                 else if (!strcasecmp(val, "strict"))
1040                         q->joinempty = QUEUE_EMPTY_STRICT;
1041                 else if (ast_true(val))
1042                         q->joinempty = QUEUE_EMPTY_NORMAL;
1043                 else
1044                         q->joinempty = 0;
1045         } else if (!strcasecmp(param, "leavewhenempty")) {
1046                 if (!strcasecmp(val, "loose"))
1047                         q->leavewhenempty = QUEUE_EMPTY_LOOSE;
1048                 else if (!strcasecmp(val, "strict"))
1049                         q->leavewhenempty = QUEUE_EMPTY_STRICT;
1050                 else if (ast_true(val))
1051                         q->leavewhenempty = QUEUE_EMPTY_NORMAL;
1052                 else
1053                         q->leavewhenempty = 0;
1054         } else if (!strcasecmp(param, "eventmemberstatus")) {
1055                 q->maskmemberstatus = !ast_true(val);
1056         } else if (!strcasecmp(param, "eventwhencalled")) {
1057                 if (!strcasecmp(val, "vars")) {
1058                         q->eventwhencalled = QUEUE_EVENT_VARIABLES;
1059                 } else {
1060                         q->eventwhencalled = ast_true(val);
1061                 }
1062         } else if (!strcasecmp(param, "reportholdtime")) {
1063                 q->reportholdtime = ast_true(val);
1064         } else if (!strcasecmp(param, "memberdelay")) {
1065                 q->memberdelay = atoi(val);
1066         } else if (!strcasecmp(param, "weight")) {
1067                 q->weight = atoi(val);
1068                 if (q->weight)
1069                         use_weight++;
1070                 /* With Realtime queues, if the last queue using weights is deleted in realtime,
1071                    we will not see any effect on use_weight until next reload. */
1072         } else if (!strcasecmp(param, "timeoutrestart")) {
1073                 q->timeoutrestart = ast_true(val);
1074         } else if (failunknown) {
1075                 if (linenum >= 0) {
1076                         ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s at line %d of queues.conf\n",
1077                                 q->name, param, linenum);
1078                 } else {
1079                         ast_log(LOG_WARNING, "Unknown keyword in queue '%s': %s\n", q->name, param);
1080                 }
1081         }
1082 }
1083
1084 static void rt_handle_member_record(struct call_queue *q, char *interface, const char *membername, const char *penalty_str, const char *paused_str)
1085 {
1086         struct member *m, tmpmem;
1087         int penalty = 0;
1088         int paused  = 0;
1089
1090         if (penalty_str) {
1091                 penalty = atoi(penalty_str);
1092                 if (penalty < 0)
1093                         penalty = 0;
1094         }
1095
1096         if (paused_str) {
1097                 paused = atoi(paused_str);
1098                 if (paused < 0)
1099                         paused = 0;
1100         }
1101
1102         /* Find the member, or the place to put a new one. */
1103         ast_copy_string(tmpmem.interface, interface, sizeof(tmpmem.interface));
1104         m = ao2_find(q->members, &tmpmem, OBJ_POINTER);
1105
1106         /* Create a new one if not found, else update penalty */
1107         if (!m) {
1108                 if ((m = create_queue_member(interface, membername, penalty, paused))) {
1109                         m->dead = 0;
1110                         m->realtime = 1;
1111                         add_to_interfaces(interface);
1112                         ao2_link(q->members, m);
1113                         q->membercount++;
1114                 }
1115         } else {
1116                 m->dead = 0;    /* Do not delete this one. */
1117                 if (paused_str)
1118                         m->paused = paused;
1119                 m->penalty = penalty;
1120                 ao2_ref(m, -1);
1121         }
1122 }
1123
1124 static void free_members(struct call_queue *q, int all)
1125 {
1126         /* Free non-dynamic members */
1127         struct member *cur;
1128         struct ao2_iterator mem_iter = ao2_iterator_init(q->members, 0);
1129
1130         while ((cur = ao2_iterator_next(&mem_iter))) {
1131                 if (all || !cur->dynamic) {
1132                         ao2_unlink(q->members, cur);
1133                         remove_from_interfaces(cur->interface);
1134                         q->membercount--;
1135                 }
1136                 ao2_ref(cur, -1);
1137         }
1138 }
1139
1140 static void destroy_queue(struct call_queue *q)
1141 {
1142         free_members(q, 1);
1143         ast_mutex_destroy(&q->lock);
1144         ao2_ref(q->members, -1);
1145         free(q);
1146 }
1147
1148 /*!\brief Reload a single queue via realtime.
1149    \return Return the queue, or NULL if it doesn't exist.
1150    \note Should be called with the global qlock locked. */
1151 static struct call_queue *find_queue_by_name_rt(const char *queuename, struct ast_variable *queue_vars, struct ast_config *member_config)
1152 {
1153         struct ast_variable *v;
1154         struct call_queue *q;
1155         struct member *m;
1156         struct ao2_iterator mem_iter;
1157         char *interface = NULL;
1158         char *tmp, *tmp_name;
1159         char tmpbuf[64];        /* Must be longer than the longest queue param name. */
1160
1161         /* Find the queue in the in-core list (we will create a new one if not found). */
1162         AST_LIST_TRAVERSE(&queues, q, list) {
1163                 if (!strcasecmp(q->name, queuename))
1164                         break;
1165         }
1166
1167         /* Static queues override realtime. */
1168         if (q) {
1169                 ast_mutex_lock(&q->lock);
1170                 if (!q->realtime) {
1171                         if (q->dead) {
1172                                 ast_mutex_unlock(&q->lock);
1173                                 return NULL;
1174                         } else {
1175                                 ast_log(LOG_WARNING, "Static queue '%s' already exists. Not loading from realtime\n", q->name);
1176                                 ast_mutex_unlock(&q->lock);
1177                                 return q;
1178                         }
1179                 }
1180         } else if (!member_config)
1181                 /* Not found in the list, and it's not realtime ... */
1182                 return NULL;
1183
1184         /* Check if queue is defined in realtime. */
1185         if (!queue_vars) {
1186                 /* Delete queue from in-core list if it has been deleted in realtime. */
1187                 if (q) {
1188                         /*! \note Hmm, can't seem to distinguish a DB failure from a not
1189                            found condition... So we might delete an in-core queue
1190                            in case of DB failure. */
1191                         ast_debug(1, "Queue %s not found in realtime.\n", queuename);
1192
1193                         q->dead = 1;
1194                         /* Delete if unused (else will be deleted when last caller leaves). */
1195                         if (!q->count) {
1196                                 /* Delete. */
1197                                 AST_LIST_REMOVE(&queues, q, list);
1198                                 ast_mutex_unlock(&q->lock);
1199                                 destroy_queue(q);
1200                         } else
1201                                 ast_mutex_unlock(&q->lock);
1202                 }
1203                 return NULL;
1204         }
1205
1206         /* Create a new queue if an in-core entry does not exist yet. */
1207         if (!q) {
1208                 if (!(q = alloc_queue(queuename)))
1209                         return NULL;
1210                 ast_mutex_lock(&q->lock);
1211                 clear_queue(q);
1212                 q->realtime = 1;
1213                 init_queue(q);          /* Ensure defaults for all parameters not set explicitly. */
1214                 AST_LIST_INSERT_HEAD(&queues, q, list);
1215         }
1216
1217         memset(tmpbuf, 0, sizeof(tmpbuf));
1218         for (v = queue_vars; v; v = v->next) {
1219                 /* Convert to dashes `-' from underscores `_' as the latter are more SQL friendly. */
1220                 if ((tmp = strchr(v->name, '_'))) {
1221                         ast_copy_string(tmpbuf, v->name, sizeof(tmpbuf));
1222                         tmp_name = tmpbuf;
1223                         tmp = tmp_name;
1224                         while ((tmp = strchr(tmp, '_')))
1225                                 *tmp++ = '-';
1226                 } else
1227                         tmp_name = v->name;
1228                 queue_set_param(q, tmp_name, v->value, -1, 0);
1229         }
1230
1231         /* Temporarily set realtime members dead so we can detect deleted ones. 
1232          * Also set the membercount correctly for realtime*/
1233         mem_iter = ao2_iterator_init(q->members, 0);
1234         while ((m = ao2_iterator_next(&mem_iter))) {
1235                 q->membercount++;
1236                 if (m->realtime)
1237                         m->dead = 1;
1238                 ao2_ref(m, -1);
1239         }
1240
1241         while ((interface = ast_category_browse(member_config, interface))) {
1242                 rt_handle_member_record(q, interface,
1243                         ast_variable_retrieve(member_config, interface, "membername"),
1244                         ast_variable_retrieve(member_config, interface, "penalty"),
1245                         ast_variable_retrieve(member_config, interface, "paused"));
1246         }
1247
1248         /* Delete all realtime members that have been deleted in DB. */
1249         mem_iter = ao2_iterator_init(q->members, 0);
1250         while ((m = ao2_iterator_next(&mem_iter))) {
1251                 if (m->dead) {
1252                         ao2_unlink(q->members, m);
1253                         ast_mutex_unlock(&q->lock);
1254                         remove_from_interfaces(m->interface);
1255                         ast_mutex_lock(&q->lock);
1256                         q->membercount--;
1257                 }
1258                 ao2_ref(m, -1);
1259         }
1260
1261         ast_mutex_unlock(&q->lock);
1262
1263         return q;
1264 }
1265
1266 static struct call_queue *load_realtime_queue(const char *queuename)
1267 {
1268         struct ast_variable *queue_vars;
1269         struct ast_config *member_config = NULL;
1270         struct call_queue *q;
1271
1272         /* Find the queue in the in-core list first. */
1273         AST_LIST_LOCK(&queues);
1274         AST_LIST_TRAVERSE(&queues, q, list) {
1275                 if (!strcasecmp(q->name, queuename)) {
1276                         break;
1277                 }
1278         }
1279         AST_LIST_UNLOCK(&queues);
1280
1281         if (!q || q->realtime) {
1282                 /*! \note Load from realtime before taking the global qlock, to avoid blocking all
1283                    queue operations while waiting for the DB.
1284
1285                    This will be two separate database transactions, so we might
1286                    see queue parameters as they were before another process
1287                    changed the queue and member list as it was after the change.
1288                    Thus we might see an empty member list when a queue is
1289                    deleted. In practise, this is unlikely to cause a problem. */
1290
1291                 queue_vars = ast_load_realtime("queues", "name", queuename, NULL);
1292                 if (queue_vars) {
1293                         member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", queuename, NULL);
1294                         if (!member_config) {
1295                                 ast_log(LOG_ERROR, "no queue_members defined in your config (extconfig.conf).\n");
1296                                 return NULL;
1297                         }
1298                 }
1299
1300                 AST_LIST_LOCK(&queues);
1301
1302                 q = find_queue_by_name_rt(queuename, queue_vars, member_config);
1303                 if (member_config)
1304                         ast_config_destroy(member_config);
1305                 if (queue_vars)
1306                         ast_variables_destroy(queue_vars);
1307
1308                 AST_LIST_UNLOCK(&queues);
1309         } else {
1310                 update_realtime_members(q);
1311         }
1312         return q;
1313 }
1314
1315 static int update_realtime_member_field(struct member *mem, const char *queue_name, const char *field, const char *value)
1316 {
1317         struct ast_variable *var;
1318         int ret = -1;
1319
1320         if(!(var = ast_load_realtime("queue_members", "interface", mem->interface, "queue_name", queue_name, NULL))) 
1321                 return ret;
1322         while (var) {
1323                 if(!strcmp(var->name, "uniqueid"))
1324                         break;
1325                 var = var->next;
1326         }
1327         if(var && !ast_strlen_zero(var->value)) {
1328                 if ((ast_update_realtime("queue_members", "uniqueid", var->value, field, value, NULL)) > -1)
1329                         ret = 0;
1330         }
1331         return ret;
1332 }
1333
1334 static void update_realtime_members(struct call_queue *q)
1335 {
1336         struct ast_config *member_config = NULL;
1337         struct member *m;
1338         char *interface = NULL;
1339         struct ao2_iterator mem_iter;
1340
1341         member_config = ast_load_realtime_multientry("queue_members", "interface LIKE", "%", "queue_name", q->name , NULL);
1342         if (!member_config) {
1343                 /*This queue doesn't have realtime members*/
1344                 ast_debug(3, "Queue %s has no realtime members defined. No need for update\n", q->name);
1345                 return;
1346         }
1347
1348         ast_mutex_lock(&q->lock);
1349         
1350         /* Temporarily set realtime  members dead so we can detect deleted ones.*/ 
1351         mem_iter = ao2_iterator_init(q->members, 0);
1352         while ((m = ao2_iterator_next(&mem_iter))) {
1353                 if (m->realtime)
1354                         m->dead = 1;
1355                 ao2_ref(m, -1);
1356         }
1357
1358         while ((interface = ast_category_browse(member_config, interface))) {
1359                 rt_handle_member_record(q, interface,
1360                         S_OR(ast_variable_retrieve(member_config, interface, "membername"), interface),
1361                         ast_variable_retrieve(member_config, interface, "penalty"),
1362                         ast_variable_retrieve(member_config, interface, "paused"));
1363         }
1364
1365         /* Delete all realtime members that have been deleted in DB. */
1366         mem_iter = ao2_iterator_init(q->members, 0);
1367         while ((m = ao2_iterator_next(&mem_iter))) {
1368                 if (m->dead) {
1369                         ao2_unlink(q->members, m);
1370                         ast_mutex_unlock(&q->lock);
1371                         remove_from_interfaces(m->interface);
1372                         ast_mutex_lock(&q->lock);
1373                         q->membercount--;
1374                 }
1375                 ao2_ref(m, -1);
1376         }
1377         ast_mutex_unlock(&q->lock);
1378 }
1379
1380 static int join_queue(char *queuename, struct queue_ent *qe, enum queue_result *reason)
1381 {
1382         struct call_queue *q;
1383         struct queue_ent *cur, *prev = NULL;
1384         int res = -1;
1385         int pos = 0;
1386         int inserted = 0;
1387         enum queue_member_status stat;
1388
1389         if (!(q = load_realtime_queue(queuename)))
1390                 return res;
1391
1392         AST_LIST_LOCK(&queues);
1393         ast_mutex_lock(&q->lock);
1394
1395         /* This is our one */
1396         stat = get_member_status(q, qe->max_penalty);
1397         if (!q->joinempty && (stat == QUEUE_NO_MEMBERS))
1398                 *reason = QUEUE_JOINEMPTY;
1399         else if ((q->joinempty == QUEUE_EMPTY_STRICT) && (stat == QUEUE_NO_REACHABLE_MEMBERS || stat == QUEUE_NO_UNPAUSED_REACHABLE_MEMBERS))
1400                 *reason = QUEUE_JOINUNAVAIL;
1401         else if ((q->joinempty == QUEUE_EMPTY_LOOSE) && (stat == QUEUE_NO_REACHABLE_MEMBERS))
1402                 *reason = QUEUE_JOINUNAVAIL;
1403         else if (q->maxlen && (q->count >= q->maxlen))
1404                 *reason = QUEUE_FULL;
1405         else {
1406                 /* There's space for us, put us at the right position inside
1407                  * the queue.
1408                  * Take into account the priority of the calling user */
1409                 inserted = 0;
1410                 prev = NULL;
1411                 cur = q->head;
1412                 while (cur) {
1413                         /* We have higher priority than the current user, enter
1414                          * before him, after all the other users with priority
1415                          * higher or equal to our priority. */
1416                         if ((!inserted) && (qe->prio > cur->prio)) {
1417                                 insert_entry(q, prev, qe, &pos);
1418                                 inserted = 1;
1419                         }
1420                         cur->pos = ++pos;
1421                         prev = cur;
1422                         cur = cur->next;
1423                 }
1424                 /* No luck, join at the end of the queue */
1425                 if (!inserted)
1426                         insert_entry(q, prev, qe, &pos);
1427                 ast_copy_string(qe->moh, q->moh, sizeof(qe->moh));
1428                 ast_copy_string(qe->announce, q->announce, sizeof(qe->announce));
1429                 ast_copy_string(qe->context, q->context, sizeof(qe->context));
1430                 q->count++;
1431                 res = 0;
1432                 manager_event(EVENT_FLAG_CALL, "Join",
1433                         "Channel: %s\r\nCallerID: %s\r\nCallerIDName: %s\r\nQueue: %s\r\nPosition: %d\r\nCount: %d\r\nUniqueid: %s\r\n",
1434                         qe->chan->name,
1435                         S_OR(qe->chan->cid.cid_num, "unknown"), /* XXX somewhere else it is <unknown> */
1436                         S_OR(qe->chan->cid.cid_name, "unknown"),
1437                         q->name, qe->pos, q->count, qe->chan->uniqueid );
1438                 ast_debug(1, "Queue '%s' Join, Channel '%s', Position '%d'\n", q->name, qe->chan->name, qe->pos );
1439         }
1440         ast_mutex_unlock(&q->lock);
1441         AST_LIST_UNLOCK(&queues);
1442
1443         return res;
1444 }
1445
1446 static int play_file(struct ast_channel *chan, char *filename)
1447 {
1448         int res;
1449
1450         ast_stopstream(chan);
1451
1452         res = ast_streamfile(chan, filename, chan->language);
1453         if (!res)
1454                 res = ast_waitstream(chan, AST_DIGIT_ANY);
1455
1456         ast_stopstream(chan);
1457
1458         return res;
1459 }
1460
1461 static int valid_exit(struct queue_ent *qe, char digit)
1462 {
1463         int digitlen = strlen(qe->digits);
1464
1465         /* Prevent possible buffer overflow */
1466         if (digitlen < sizeof(qe->digits) - 2) {
1467                 qe->digits[digitlen] = digit;
1468                 qe->digits[digitlen + 1] = '\0';
1469         } else {
1470                 qe->digits[0] = '\0';
1471                 return 0;
1472         }
1473
1474         /* If there's no context to goto, short-circuit */
1475         if (ast_strlen_zero(qe->context))
1476                 return 0;
1477
1478         /* If the extension is bad, then reset the digits to blank */
1479         if (!ast_canmatch_extension(qe->chan, qe->context, qe->digits, 1, qe->chan->cid.cid_num)) {
1480                 qe->digits[0] = '\0';
1481                 return 0;
1482         }
1483
1484         /* We have an exact match */
1485         if (!ast_goto_if_exists(qe->chan, qe->context, qe->digits, 1)) {
1486                 qe->valid_digits = 1;
1487                 /* Return 1 on a successful goto */
1488                 return 1;
1489         }
1490
1491         return 0;
1492 }
1493
1494 static int say_position(struct queue_ent *qe, int ringing)
1495 {
1496         int res = 0, avgholdmins, avgholdsecs;
1497         time_t now;
1498
1499         /* Let minannouncefrequency seconds pass between the start of each position announcement */
1500         time(&now);
1501         if ((now - qe->last_pos) < qe->parent->minannouncefrequency)
1502                 return 0;
1503
1504         /* If either our position has changed, or we are over the freq timer, say position */
1505         if ((qe->last_pos_said == qe->pos) && ((now - qe->last_pos) < qe->parent->announcefrequency))
1506                 return 0;
1507
1508         if (ringing) {
1509                 ast_indicate(qe->chan,-1);
1510         } else {
1511                 ast_moh_stop(qe->chan);
1512         }
1513         /* Say we're next, if we are */
1514         if (qe->pos == 1) {
1515                 res = play_file(qe->chan, qe->parent->sound_next);
1516                 if (res)
1517                         goto playout;
1518                 else
1519                         goto posout;
1520         } else {
1521                 res = play_file(qe->chan, qe->parent->sound_thereare);
1522                 if (res)
1523                         goto playout;
1524                 res = ast_say_number(qe->chan, qe->pos, AST_DIGIT_ANY, qe->chan->language, (char *) NULL); /* Needs gender */
1525                 if (res)
1526                         goto playout;
1527                 res = play_file(qe->chan, qe->parent->sound_calls);
1528                 if (res)
1529                         goto playout;
1530         }
1531         /* Round hold time to nearest minute */
1532         avgholdmins = abs(((qe->parent->holdtime + 30) - (now - qe->start)) / 60);
1533
1534         /* If they have specified a rounding then round the seconds as well */
1535         if (qe->parent->roundingseconds) {
1536                 avgholdsecs = (abs(((qe->parent->holdtime + 30) - (now - qe->start))) - 60 * avgholdmins) / qe->parent->roundingseconds;
1537                 avgholdsecs *= qe->parent->roundingseconds;
1538         } else {
1539                 avgholdsecs = 0;
1540         }
1541
1542         ast_verb(3, "Hold time for %s is %d minutes %d seconds\n", qe->parent->name, avgholdmins, avgholdsecs);
1543
1544         /* If the hold time is >1 min, if it's enabled, and if it's not
1545            supposed to be only once and we have already said it, say it */
1546         if ((avgholdmins+avgholdsecs) > 0 && (qe->parent->announceholdtime) &&
1547                 (!(qe->parent->announceholdtime == ANNOUNCEHOLDTIME_ONCE) && qe->last_pos)) {
1548                 res = play_file(qe->chan, qe->parent->sound_holdtime);
1549                 if (res)
1550                         goto playout;
1551
1552                 if (avgholdmins > 0) {
1553                         if (avgholdmins < 2) {
1554                                 res = play_file(qe->chan, qe->parent->sound_lessthan);
1555                                 if (res)
1556                                         goto playout;
1557
1558                                 res = ast_say_number(qe->chan, 2, AST_DIGIT_ANY, qe->chan->language, NULL);
1559                                 if (res)
1560                                         goto playout;
1561                         } else {
1562                                 res = ast_say_number(qe->chan, avgholdmins, AST_DIGIT_ANY, qe->chan->language, NULL);
1563                                 if (res)
1564                                         goto playout;
1565                         }
1566                         
1567                         res = play_file(qe->chan, qe->parent->sound_minutes);
1568                         if (res)
1569                                 goto playout;
1570                 }
1571                 if (avgholdsecs>0) {
1572                         res = ast_say_number(qe->chan, avgholdsecs, AST_DIGIT_ANY, qe->chan->language, NULL);
1573                         if (res)
1574                                 goto playout;
1575
1576                         res = play_file(qe->chan, qe->parent->sound_seconds);
1577                         if (res)
1578                                 goto playout;
1579                 }
1580
1581         }
1582
1583 posout:
1584         ast_verb(3, "Told %s in %s their queue position (which was %d)\n",
1585                         qe->chan->name, qe->parent->name, qe->pos);
1586         res = play_file(qe->chan, qe->parent->sound_thanks);
1587
1588 playout:
1589         if (res > 0 && !valid_exit(qe, res))
1590                 res = 0;
1591
1592         /* Set our last_pos indicators */
1593         qe->last_pos = now;
1594         qe->last_pos_said = qe->pos;
1595
1596         /* Don't restart music on hold if we're about to exit the caller from the queue */
1597         if (!res) {
1598                 if (ringing)
1599                         ast_indicate(qe->chan, AST_CONTROL_RINGING);
1600                 else
1601                         ast_moh_start(qe->chan, qe->moh, NULL);
1602         }
1603         return res;
1604 }
1605
1606 static void recalc_holdtime(struct queue_ent *qe, int newholdtime)
1607 {
1608         int oldvalue;
1609
1610         /* Calculate holdtime using a recursive boxcar filter */
1611         /* Thanks to SRT for this contribution */
1612         /* 2^2 (4) is the filter coefficient; a higher exponent would give old entries more weight */
1613
1614         ast_mutex_lock(&qe->parent->lock);
1615         oldvalue = qe->parent->holdtime;
1616         qe->parent->holdtime = (((oldvalue << 2) - oldvalue) + newholdtime) >> 2;
1617         ast_mutex_unlock(&qe->parent->lock);
1618 }
1619
1620
1621 static void leave_queue(struct queue_ent *qe)
1622 {
1623         struct call_queue *q;
1624         struct queue_ent *cur, *prev = NULL;
1625         int pos = 0;
1626
1627         if (!(q = qe->parent))
1628                 return;
1629         ast_mutex_lock(&q->lock);
1630
1631         prev = NULL;
1632         for (cur = q->head; cur; cur = cur->next) {
1633                 if (cur == qe) {
1634                         q->count--;
1635
1636                         /* Take us out of the queue */
1637                         manager_event(EVENT_FLAG_CALL, "Leave",
1638                                 "Channel: %s\r\nQueue: %s\r\nCount: %d\r\nUniqueid: %s\r\n",
1639                                 qe->chan->name, q->name,  q->count, qe->chan->uniqueid);
1640                         ast_debug(1, "Queue '%s' Leave, Channel '%s'\n", q->name, qe->chan->name );
1641                         /* Take us out of the queue */
1642                         if (prev)
1643                                 prev->next = cur->next;
1644                         else
1645                                 q->head = cur->next;
1646                 } else {
1647                         /* Renumber the people after us in the queue based on a new count */
1648                         cur->pos = ++pos;
1649                         prev = cur;
1650                 }
1651         }
1652         ast_mutex_unlock(&q->lock);
1653
1654         if (q->dead && !q->count) {     
1655                 /* It's dead and nobody is in it, so kill it */
1656                 AST_LIST_LOCK(&queues);
1657                 AST_LIST_REMOVE(&queues, q, list);
1658                 AST_LIST_UNLOCK(&queues);
1659                 destroy_queue(q);
1660         }
1661 }
1662
1663 /* Hang up a list of outgoing calls */
1664 static void hangupcalls(struct callattempt *outgoing, struct ast_channel *exception)
1665 {
1666         struct callattempt *oo;
1667
1668         while (outgoing) {
1669                 /* Hangup any existing lines we have open */
1670                 if (outgoing->chan && (outgoing->chan != exception))
1671                         ast_hangup(outgoing->chan);
1672                 oo = outgoing;
1673                 outgoing = outgoing->q_next;
1674                 if (oo->member)
1675                         ao2_ref(oo->member, -1);
1676                 ast_free(oo);
1677         }
1678 }
1679
1680 static int update_status(struct call_queue *q, struct member *member, int status)
1681 {
1682         struct member *cur;
1683         struct ao2_iterator mem_iter;
1684
1685         /* Since a reload could have taken place, we have to traverse the list to
1686                 be sure it's still valid */
1687         ast_mutex_lock(&q->lock);
1688         mem_iter = ao2_iterator_init(q->members, 0);
1689         while ((cur = ao2_iterator_next(&mem_iter))) {
1690                 if (member != cur) {
1691                         ao2_ref(cur, -1);
1692                         continue;
1693                 }
1694
1695                 cur->status = status;
1696                 if (!q->maskmemberstatus) {
1697                         manager_event(EVENT_FLAG_AGENT, "QueueMemberStatus",
1698                                 "Queue: %s\r\n"
1699                                 "Location: %s\r\n"
1700                                 "MemberName: %s\r\n"
1701                                 "Membership: %s\r\n"
1702                                 "Penalty: %d\r\n"
1703                                 "CallsTaken: %d\r\n"
1704                                 "LastCall: %d\r\n"
1705                                 "Status: %d\r\n"
1706                                 "Paused: %d\r\n",
1707                                 q->name, cur->interface, cur->membername, cur->dynamic ? "dynamic" : cur->realtime ? "realtime": "static",
1708                                 cur->penalty, cur->calls, (int)cur->lastcall, cur->status, cur->paused);
1709                 }
1710                 ao2_ref(cur, -1);
1711         }
1712         ast_mutex_unlock(&q->lock);
1713         return 0;
1714 }
1715
1716 static int update_dial_status(struct call_queue *q, struct member *member, int status)
1717 {
1718         if (status == AST_CAUSE_BUSY)
1719                 status = AST_DEVICE_BUSY;
1720         else if (status == AST_CAUSE_UNREGISTERED)
1721                 status = AST_DEVICE_UNAVAILABLE;
1722         else if (status == AST_CAUSE_NOSUCHDRIVER)
1723                 status = AST_DEVICE_INVALID;
1724         else
1725                 status = AST_DEVICE_UNKNOWN;
1726         return update_status(q, member, status);
1727 }
1728
1729 /* traverse all defined queues which have calls waiting and contain this member
1730    return 0 if no other queue has precedence (higher weight) or 1 if found  */
1731 static int compare_weight(struct call_queue *rq, struct member *member)
1732 {
1733         struct call_queue *q;
1734         struct member *mem;
1735         int found = 0;
1736         
1737         /* &qlock and &rq->lock already set by try_calling()
1738          * to solve deadlock */
1739         AST_LIST_TRAVERSE(&queues, q, list) {
1740                 if (q == rq) /* don't check myself, could deadlock */
1741                         continue;
1742                 ast_mutex_lock(&q->lock);
1743                 if (q->count && q->members) {
1744                         if ((mem = ao2_find(q->members, member, OBJ_POINTER))) {
1745                                 ast_debug(1, "Found matching member %s in queue '%s'\n", mem->interface, q->name);
1746                                 if (q->weight > rq->weight) {
1747                                         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);
1748                                         found = 1;
1749                                 }
1750                                 ao2_ref(mem, -1);
1751                         }
1752                 }
1753                 ast_mutex_unlock(&q->lock);
1754                 if (found)
1755                         break;
1756         }
1757         return found;
1758 }
1759
1760 /*! \brief common hangup actions */
1761 static void do_hang(struct callattempt *o)
1762 {
1763         o->stillgoing = 0;
1764         ast_hangup(o->chan);
1765         o->chan = NULL;
1766 }
1767
1768 static char *vars2manager(struct ast_channel *chan, char *vars, size_t len)
1769 {
1770         struct ast_str *buf = ast_str_alloca(len + 1);
1771         char *tmp;
1772
1773         if (pbx_builtin_serialize_variables(chan, &buf)) {
1774                 int i, j;
1775
1776                 /* convert "\n" to "\nVariable: " */
1777                 strcpy(vars, "Variable: ");
1778                 tmp = buf->str;
1779
1780                 for (i = 0, j = 10; (i < len - 1) && (j < len - 1); i++, j++) {
1781                         vars[j] = tmp[i];
1782
1783                         if (tmp[i + 1] == '\0')
1784                                 break;
1785                         if (tmp[i] == '\n') {
1786                                 vars[j] = '\r';
1787                                 vars[++j] = '\n';
1788
1789                                 ast_copy_string(&(vars[j]), "Variable: ", len - j);
1790                                 j += 9;
1791                         }
1792                 }
1793                 if (j > len - 1)
1794                         j = len - 1;
1795                 vars[j - 2] = '\r';
1796                 vars[j - 1] = '\n';
1797                 vars[j] = '\0';
1798         } else {
1799                 /* there are no channel variables; leave it blank */
1800                 *vars = '\0';
1801         }
1802         return vars;
1803 }
1804
1805 static int ring_entry(struct queue_ent *qe, struct callattempt *tmp, int *busies)
1806 {
1807         int res;
1808         int status;
1809         char tech[256];
1810         char *location;
1811
1812         /* on entry here, we know that tmp->chan == NULL */
1813         if (qe->parent->wrapuptime && (time(NULL) - tmp->lastcall < qe->parent->wrapuptime)) {
1814                 ast_debug(1, "Wrapuptime not yet expired for %s\n", tmp->interface);
1815                 if (qe->chan->cdr)
1816                         ast_cdr_busy(qe->chan->cdr);
1817                 tmp->stillgoing = 0;
1818                 (*busies)++;
1819                 return 0;
1820         }
1821
1822         if (!qe->parent->ringinuse && (tmp->member->status != AST_DEVICE_NOT_INUSE) && (tmp->member->status != AST_DEVICE_UNKNOWN)) {
1823                 ast_debug(1, "%s in use, can't receive call\n", tmp->interface);
1824                 if (qe->chan->cdr)
1825                         ast_cdr_busy(qe->chan->cdr);
1826                 tmp->stillgoing = 0;
1827                 return 0;
1828         }
1829
1830         if (tmp->member->paused) {
1831                 ast_debug(1, "%s paused, can't receive call\n", tmp->interface);
1832                 if (qe->chan->cdr)
1833                         ast_cdr_busy(qe->chan->cdr);
1834                 tmp->stillgoing = 0;
1835                 return 0;
1836         }
1837         if (use_weight && compare_weight(qe->parent,tmp->member)) {
1838                 ast_debug(1, "Priority queue delaying call to %s:%s\n", qe->parent->name, tmp->interface);
1839                 if (qe->chan->cdr)
1840                         ast_cdr_busy(qe->chan->cdr);
1841                 tmp->stillgoing = 0;
1842                 (*busies)++;
1843                 return 0;
1844         }
1845
1846         ast_copy_string(tech, tmp->interface, sizeof(tech));
1847         if ((location = strchr(tech, '/')))
1848                 *location++ = '\0';
1849         else
1850                 location = "";
1851
1852         /* Request the peer */
1853         tmp->chan = ast_request(tech, qe->chan->nativeformats, location, &status);
1854         if (!tmp->chan) {                       /* If we can't, just go on to the next call */
1855                 if (qe->chan->cdr)
1856                         ast_cdr_busy(qe->chan->cdr);
1857                 tmp->stillgoing = 0;
1858                 update_dial_status(qe->parent, tmp->member, status);
1859
1860                 ast_mutex_lock(&qe->parent->lock);
1861                 qe->parent->rrpos++;
1862                 ast_mutex_unlock(&qe->parent->lock);
1863
1864                 (*busies)++;
1865                 return 0;
1866         } else if (status != tmp->oldstatus)
1867                 update_dial_status(qe->parent, tmp->member, status);
1868         
1869         tmp->chan->appl = "AppQueue";
1870         tmp->chan->data = "(Outgoing Line)";
1871         tmp->chan->whentohangup = 0;
1872         if (tmp->chan->cid.cid_num)
1873                 ast_free(tmp->chan->cid.cid_num);
1874         tmp->chan->cid.cid_num = ast_strdup(qe->chan->cid.cid_num);
1875         if (tmp->chan->cid.cid_name)
1876                 ast_free(tmp->chan->cid.cid_name);
1877         tmp->chan->cid.cid_name = ast_strdup(qe->chan->cid.cid_name);
1878         if (tmp->chan->cid.cid_ani)
1879                 ast_free(tmp->chan->cid.cid_ani);
1880         tmp->chan->cid.cid_ani = ast_strdup(qe->chan->cid.cid_ani);
1881
1882         /* Inherit specially named variables from parent channel */
1883         ast_channel_inherit_variables(qe->chan, tmp->chan);
1884
1885         /* Presense of ADSI CPE on outgoing channel follows ours */
1886         tmp->chan->adsicpe = qe->chan->adsicpe;
1887
1888         /* Place the call, but don't wait on the answer */
1889         if ((res = ast_call(tmp->chan, location, 0))) {
1890                 /* Again, keep going even if there's an error */
1891                 ast_debug(1, "ast call on peer returned %d\n", res);
1892                 ast_verb(3, "Couldn't call %s\n", tmp->interface);
1893                 do_hang(tmp);
1894                 (*busies)++;
1895                 return 0;
1896         } else if (qe->parent->eventwhencalled) {
1897                 char vars[2048];
1898
1899                 manager_event(EVENT_FLAG_AGENT, "AgentCalled",
1900                                         "Queue: %s\r\n"
1901                                         "AgentCalled: %s\r\n"
1902                                         "AgentName: %s\r\n"
1903                                         "ChannelCalling: %s\r\n"
1904                                         "DestinationChannel: %s\r\n"
1905                                         "CallerIDNum: %s\r\n"
1906                                         "CallerIDName: %s\r\n"
1907                                         "Context: %s\r\n"
1908                                         "Extension: %s\r\n"
1909                                         "Priority: %d\r\n"
1910                                         "%s",
1911                                         qe->parent->name, tmp->interface, tmp->member->membername, qe->chan->name, tmp->chan->name,
1912                                         tmp->chan->cid.cid_num ? tmp->chan->cid.cid_num : "unknown",
1913                                         tmp->chan->cid.cid_name ? tmp->chan->cid.cid_name : "unknown",
1914                                         qe->chan->context, qe->chan->exten, qe->chan->priority,
1915                                         qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
1916                 ast_verb(3, "Called %s\n", tmp->interface);
1917         }
1918
1919         return 1;
1920 }
1921
1922 /*! \brief find the entry with the best metric, or NULL */
1923 static struct callattempt *find_best(struct callattempt *outgoing)
1924 {
1925         struct callattempt *best = NULL, *cur;
1926
1927         for (cur = outgoing; cur; cur = cur->q_next) {
1928                 if (cur->stillgoing &&                                  /* Not already done */
1929                         !cur->chan &&                                   /* Isn't already going */
1930                         (!best || cur->metric < best->metric)) {                /* We haven't found one yet, or it's better */
1931                         best = cur;
1932                 }
1933         }
1934
1935         return best;
1936 }
1937
1938 static int ring_one(struct queue_ent *qe, struct callattempt *outgoing, int *busies)
1939 {
1940         int ret = 0;
1941
1942         while (ret == 0) {
1943                 struct callattempt *best = find_best(outgoing);
1944                 if (!best) {
1945                         ast_debug(1, "Nobody left to try ringing in queue\n");
1946                         break;
1947                 }
1948                 if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
1949                         struct callattempt *cur;
1950                         /* Ring everyone who shares this best metric (for ringall) */
1951                         for (cur = outgoing; cur; cur = cur->q_next) {
1952                                 if (cur->stillgoing && !cur->chan && cur->metric <= best->metric) {
1953                                         ast_debug(1, "(Parallel) Trying '%s' with metric %d\n", cur->interface, cur->metric);
1954                                         ring_entry(qe, cur, busies);
1955                                 }
1956                         }
1957                 } else {
1958                         /* Ring just the best channel */
1959                         ast_debug(1, "Trying '%s' with metric %d\n", best->interface, best->metric);
1960                         ring_entry(qe, best, busies);
1961                 }
1962                 if (best->chan) /* break out with result = 1 */
1963                         ret = 1;
1964         }
1965
1966         return ret;
1967 }
1968
1969 static int store_next(struct queue_ent *qe, struct callattempt *outgoing)
1970 {
1971         struct callattempt *best = find_best(outgoing);
1972
1973         if (best) {
1974                 /* Ring just the best channel */
1975                 ast_debug(1, "Next is '%s' with metric %d\n", best->interface, best->metric);
1976                 qe->parent->rrpos = best->metric % 1000;
1977         } else {
1978                 /* Just increment rrpos */
1979                 if (qe->parent->wrapped) {
1980                         /* No more channels, start over */
1981                         qe->parent->rrpos = 0;
1982                 } else {
1983                         /* Prioritize next entry */
1984                         qe->parent->rrpos++;
1985                 }
1986         }
1987         qe->parent->wrapped = 0;
1988
1989         return 0;
1990 }
1991
1992 static int say_periodic_announcement(struct queue_ent *qe, int ringing)
1993 {
1994         int res = 0;
1995         time_t now;
1996
1997         /* Get the current time */
1998         time(&now);
1999
2000         /* Check to see if it is time to announce */
2001         if ((now - qe->last_periodic_announce_time) < qe->parent->periodicannouncefrequency)
2002                 return 0;
2003
2004         /* Stop the music on hold so we can play our own file */
2005         if (ringing)
2006                 ast_indicate(qe->chan,-1);
2007         else
2008                 ast_moh_stop(qe->chan);
2009
2010         ast_verb(3, "Playing periodic announcement\n");
2011
2012         /* Check to make sure we have a sound file. If not, reset to the first sound file */
2013         if (qe->last_periodic_announce_sound >= MAX_PERIODIC_ANNOUNCEMENTS || ast_strlen_zero(qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound])) {
2014                 qe->last_periodic_announce_sound = 0;
2015         }
2016         
2017         /* play the announcement */
2018         res = play_file(qe->chan, qe->parent->sound_periodicannounce[qe->last_periodic_announce_sound]);
2019
2020         if (res > 0 && !valid_exit(qe, res))
2021                 res = 0;
2022
2023         /* Resume Music on Hold if the caller is going to stay in the queue */
2024         if (!res) {
2025                 if (ringing)
2026                         ast_indicate(qe->chan, AST_CONTROL_RINGING);
2027                 else
2028                         ast_moh_start(qe->chan, qe->moh, NULL);
2029         }
2030
2031         /* update last_periodic_announce_time */
2032         qe->last_periodic_announce_time = now;
2033
2034         /* Update the current periodic announcement to the next announcement */
2035         qe->last_periodic_announce_sound++;
2036         
2037         return res;
2038 }
2039
2040 static void record_abandoned(struct queue_ent *qe)
2041 {
2042         ast_mutex_lock(&qe->parent->lock);
2043         set_queue_variables(qe);
2044         manager_event(EVENT_FLAG_AGENT, "QueueCallerAbandon",
2045                 "Queue: %s\r\n"
2046                 "Uniqueid: %s\r\n"
2047                 "Position: %d\r\n"
2048                 "OriginalPosition: %d\r\n"
2049                 "HoldTime: %d\r\n",
2050                 qe->parent->name, qe->chan->uniqueid, qe->pos, qe->opos, (int)(time(NULL) - qe->start));
2051
2052         qe->parent->callsabandoned++;
2053         ast_mutex_unlock(&qe->parent->lock);
2054 }
2055
2056 /*! \brief RNA == Ring No Answer. Common code that is executed when we try a queue member and they don't answer. */
2057 static void rna(int rnatime, struct queue_ent *qe, char *interface, char *membername)
2058 {
2059         ast_verb(3, "Nobody picked up in %d ms\n", rnatime);
2060         ast_queue_log(qe->parent->name, qe->chan->uniqueid, membername, "RINGNOANSWER", "%d", rnatime);
2061         if (qe->parent->autopause) {
2062                 if (!set_member_paused(qe->parent->name, interface, "Auto-Pause", 1)) {
2063                         ast_verb(3, "Auto-Pausing Queue Member %s in queue %s since they failed to answer.\n", interface, qe->parent->name);
2064                 } else {
2065                         ast_verb(3, "Failed to pause Queue Member %s in queue %s!\n", interface, qe->parent->name);
2066                 }
2067         }
2068         return;
2069 }
2070
2071 #define AST_MAX_WATCHERS 256
2072
2073 static struct callattempt *wait_for_answer(struct queue_ent *qe, struct callattempt *outgoing, int *to, char *digit, int prebusies, int caller_disconnect, int forwardsallowed)
2074 {
2075         char *queue = qe->parent->name;
2076         struct callattempt *o;
2077         int status;
2078         int sentringing = 0;
2079         int numbusies = prebusies;
2080         int numnochan = 0;
2081         int stillgoing = 0;
2082         int orig = *to;
2083         struct ast_frame *f;
2084         struct callattempt *peer = NULL;
2085         struct ast_channel *winner;
2086         struct ast_channel *in = qe->chan;
2087         char on[80] = "";
2088         char membername[80] = "";
2089         long starttime = 0;
2090         long endtime = 0;
2091 #ifdef HAVE_EPOLL
2092         struct callattempt *epollo;
2093 #endif
2094
2095         starttime = (long) time(NULL);
2096 #ifdef HAVE_EPOLL
2097         for (epollo = outgoing; epollo; epollo = epollo->q_next) {
2098                 if(epollo->chan)
2099                         ast_poll_channel_add(in, epollo->chan);
2100         }
2101 #endif
2102         
2103         while (*to && !peer) {
2104                 int numlines, retry, pos = 1;
2105                 struct ast_channel *watchers[AST_MAX_WATCHERS];
2106                 watchers[0] = in;
2107
2108                 for (retry = 0; retry < 2; retry++) {
2109                         numlines = 0;
2110                         for (o = outgoing; o; o = o->q_next) { /* Keep track of important channels */
2111                                 if (o->stillgoing) {    /* Keep track of important channels */
2112                                         stillgoing = 1;
2113                                         if (o->chan)
2114                                                 watchers[pos++] = o->chan;
2115                                 }
2116                                 numlines++;
2117                         }
2118                         if (pos > 1 /* found */ || !stillgoing /* nobody listening */ ||
2119                                 (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) /* ring would not be delivered */)
2120                                 break;
2121                         /* On "ringall" strategy we only move to the next penalty level
2122                            when *all* ringing phones are done in the current penalty level */
2123                         ring_one(qe, outgoing, &numbusies);
2124                         /* and retry... */
2125                 }
2126                 if (pos == 1 /* not found */) {
2127                         if (numlines == (numbusies + numnochan)) {
2128                                 ast_debug(1, "Everyone is busy at this time\n");
2129                         } else {
2130                                 ast_log(LOG_NOTICE, "No one is answering queue '%s' (%d/%d/%d)\n", queue, numlines, numbusies, numnochan);
2131                         }
2132                         *to = 0;
2133                         return NULL;
2134                 }
2135                 winner = ast_waitfor_n(watchers, pos, to);
2136                 for (o = outgoing; o; o = o->q_next) {
2137                         if (o->stillgoing && (o->chan) &&  (o->chan->_state == AST_STATE_UP)) {
2138                                 if (!peer) {
2139                                         ast_verb(3, "%s answered %s\n", o->chan->name, in->name);
2140                                         peer = o;
2141                                 }
2142                         } else if (o->chan && (o->chan == winner)) {
2143
2144                                 ast_copy_string(on, o->member->interface, sizeof(on));
2145                                 ast_copy_string(membername, o->member->membername, sizeof(membername));
2146
2147                                 if (!ast_strlen_zero(o->chan->call_forward) && !forwardsallowed) {
2148                                         ast_verb(3, "Forwarding %s to '%s' prevented.\n", in->name, o->chan->call_forward);
2149                                         numnochan++;
2150                                         do_hang(o);
2151                                         winner = NULL;
2152                                         continue;
2153                                 } else if (!ast_strlen_zero(o->chan->call_forward)) {
2154                                         char tmpchan[256];
2155                                         char *stuff;
2156                                         char *tech;
2157
2158                                         ast_copy_string(tmpchan, o->chan->call_forward, sizeof(tmpchan));
2159                                         if ((stuff = strchr(tmpchan, '/'))) {
2160                                                 *stuff++ = '\0';
2161                                                 tech = tmpchan;
2162                                         } else {
2163                                                 snprintf(tmpchan, sizeof(tmpchan), "%s@%s", o->chan->call_forward, o->chan->context);
2164                                                 stuff = tmpchan;
2165                                                 tech = "Local";
2166                                         }
2167                                         /* Before processing channel, go ahead and check for forwarding */
2168                                         ast_verb(3, "Now forwarding %s to '%s/%s' (thanks to %s)\n", in->name, tech, stuff, o->chan->name);
2169                                         /* Setup parameters */
2170                                         o->chan = ast_request(tech, in->nativeformats, stuff, &status);
2171                                         if (status != o->oldstatus)
2172                                                 update_dial_status(qe->parent, o->member, status);                                              
2173                                         if (!o->chan) {
2174                                                 ast_log(LOG_NOTICE, "Unable to create local channel for call forward to '%s/%s'\n", tech, stuff);
2175                                                 o->stillgoing = 0;
2176                                                 numnochan++;
2177                                         } else {
2178                                                 ast_channel_inherit_variables(in, o->chan);
2179                                                 if (o->chan->cid.cid_num)
2180                                                         ast_free(o->chan->cid.cid_num);
2181                                                 o->chan->cid.cid_num = ast_strdup(in->cid.cid_num);
2182
2183                                                 if (o->chan->cid.cid_name)
2184                                                         ast_free(o->chan->cid.cid_name);
2185                                                 o->chan->cid.cid_name = ast_strdup(in->cid.cid_name);
2186
2187                                                 ast_string_field_set(o->chan, accountcode, in->accountcode);
2188                                                 o->chan->cdrflags = in->cdrflags;
2189
2190                                                 if (in->cid.cid_ani) {
2191                                                         if (o->chan->cid.cid_ani)
2192                                                                 ast_free(o->chan->cid.cid_ani);
2193                                                         o->chan->cid.cid_ani = ast_strdup(in->cid.cid_ani);
2194                                                 }
2195                                                 if (o->chan->cid.cid_rdnis)
2196                                                         ast_free(o->chan->cid.cid_rdnis);
2197                                                 o->chan->cid.cid_rdnis = ast_strdup(S_OR(in->macroexten, in->exten));
2198                                                 if (ast_call(o->chan, tmpchan, 0)) {
2199                                                         ast_log(LOG_NOTICE, "Failed to dial on local channel for call forward to '%s'\n", tmpchan);
2200                                                         do_hang(o);
2201                                                         numnochan++;
2202                                                 }
2203                                         }
2204                                         /* Hangup the original channel now, in case we needed it */
2205                                         ast_hangup(winner);
2206                                         continue;
2207                                 }
2208                                 f = ast_read(winner);
2209                                 if (f) {
2210                                         if (f->frametype == AST_FRAME_CONTROL) {
2211                                                 switch (f->subclass) {
2212                                                 case AST_CONTROL_ANSWER:
2213                                                         /* This is our guy if someone answered. */
2214                                                         if (!peer) {
2215                                                                 ast_verb(3, "%s answered %s\n", o->chan->name, in->name);
2216                                                                 peer = o;
2217                                                         }
2218                                                         break;
2219                                                 case AST_CONTROL_BUSY:
2220                                                         ast_verb(3, "%s is busy\n", o->chan->name);
2221                                                         if (in->cdr)
2222                                                                 ast_cdr_busy(in->cdr);
2223                                                         do_hang(o);
2224                                                         endtime = (long) time(NULL);
2225                                                         endtime -= starttime;
2226                                                         rna(endtime*1000, qe, on, membername);
2227                                                         if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
2228                                                                 if (qe->parent->timeoutrestart)
2229                                                                         *to = orig;
2230                                                                 ring_one(qe, outgoing, &numbusies);
2231                                                         }
2232                                                         numbusies++;
2233                                                         break;
2234                                                 case AST_CONTROL_CONGESTION:
2235                                                         ast_verb(3, "%s is circuit-busy\n", o->chan->name);
2236                                                         if (in->cdr)
2237                                                                 ast_cdr_busy(in->cdr);
2238                                                         endtime = (long) time(NULL);
2239                                                         endtime -= starttime;
2240                                                         rna(endtime*1000, qe, on, membername);
2241                                                         do_hang(o);
2242                                                         if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
2243                                                                 if (qe->parent->timeoutrestart)
2244                                                                         *to = orig;
2245                                                                 ring_one(qe, outgoing, &numbusies);
2246                                                         }
2247                                                         numbusies++;
2248                                                         break;
2249                                                 case AST_CONTROL_RINGING:
2250                                                         ast_verb(3, "%s is ringing\n", o->chan->name);
2251                                                         if (!sentringing) {
2252 #if 0
2253                                                                 ast_indicate(in, AST_CONTROL_RINGING);
2254 #endif                                                          
2255                                                                 sentringing++;
2256                                                         }
2257                                                         break;
2258                                                 case AST_CONTROL_OFFHOOK:
2259                                                         /* Ignore going off hook */
2260                                                         break;
2261                                                 default:
2262                                                         ast_debug(1, "Dunno what to do with control type %d\n", f->subclass);
2263                                                 }
2264                                         }
2265                                         ast_frfree(f);
2266                                 } else {
2267                                         endtime = (long) time(NULL) - starttime;
2268                                         rna(endtime * 1000, qe, on, membername);
2269                                         do_hang(o);
2270                                         if (qe->parent->strategy != QUEUE_STRATEGY_RINGALL) {
2271                                                 if (qe->parent->timeoutrestart)
2272                                                         *to = orig;
2273                                                 ring_one(qe, outgoing, &numbusies);
2274                                         }
2275                                 }
2276                         }
2277                 }
2278                 if (winner == in) {
2279                         f = ast_read(in);
2280                         if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))) {
2281                                 /* Got hung up */
2282                                 *to = -1;
2283                                 if (f)
2284                                         ast_frfree(f);
2285                                 return NULL;
2286                         }
2287                         if ((f->frametype == AST_FRAME_DTMF) && caller_disconnect && (f->subclass == '*')) {
2288                                 ast_verb(3, "User hit %c to disconnect call.\n", f->subclass);
2289                                 *to = 0;
2290                                 ast_frfree(f);
2291                                 return NULL;
2292                         }
2293                         if ((f->frametype == AST_FRAME_DTMF) && valid_exit(qe, f->subclass)) {
2294                                 ast_verb(3, "User pressed digit: %c\n", f->subclass);
2295                                 *to = 0;
2296                                 *digit = f->subclass;
2297                                 ast_frfree(f);
2298                                 return NULL;
2299                         }
2300                         ast_frfree(f);
2301                 }
2302                 if (!*to)
2303                         rna(orig, qe, on, membername);
2304         }
2305
2306 #ifdef HAVE_EPOLL
2307         for(epollo = outgoing; epollo; epollo = epollo->q_next) {
2308                 if(epollo->chan)
2309                         ast_poll_channel_del(in, epollo->chan);
2310         }
2311 #endif
2312
2313         return peer;
2314 }
2315
2316 static int is_our_turn(struct queue_ent *qe)
2317 {
2318         struct queue_ent *ch;
2319         struct member *cur;
2320         int avl = 0;
2321         int idx = 0;
2322         int res;
2323
2324         if (!qe->parent->autofill) {
2325                 /* Atomically read the parent head -- does not need a lock */
2326                 ch = qe->parent->head;
2327                 /* If we are now at the top of the head, break out */
2328                 if (ch == qe) {
2329                         ast_debug(1, "It's our turn (%s).\n", qe->chan->name);
2330                         res = 1;
2331                 } else {
2332                         ast_debug(1, "It's not our turn (%s).\n", qe->chan->name);
2333                         res = 0;
2334                 }       
2335
2336         } else {
2337                 /* This needs a lock. How many members are available to be served? */
2338                 ast_mutex_lock(&qe->parent->lock);
2339                         
2340                 ch = qe->parent->head;
2341         
2342                 if (qe->parent->strategy == QUEUE_STRATEGY_RINGALL) {
2343                         ast_debug(1, "Even though there are %d available members, the strategy is ringall so only the head call is allowed in\n", avl);
2344                         avl = 1;
2345                 } else {
2346                         struct ao2_iterator mem_iter = ao2_iterator_init(qe->parent->members, 0);
2347                         while ((cur = ao2_iterator_next(&mem_iter))) {
2348                                 switch (cur->status) {
2349                                 case AST_DEVICE_NOT_INUSE:
2350                                 case AST_DEVICE_UNKNOWN:
2351                                         if (!cur->paused)
2352                                                 avl++;
2353                                         break;
2354                                 }
2355                                 ao2_ref(cur, -1);
2356                         }
2357                 }
2358
2359                 ast_debug(1, "There are %d available members.\n", avl);
2360         
2361                 while ((idx < avl) && (ch) && (ch != qe)) {
2362                         idx++;
2363                         ch = ch->next;                  
2364                 }
2365         
2366                 /* If the queue entry is within avl [the number of available members] calls from the top ... */
2367                 if (ch && idx < avl) {
2368                         ast_debug(1, "It's our turn (%s).\n", qe->chan->name);
2369                         res = 1;
2370                 } else {
2371                         ast_debug(1, "It's not our turn (%s).\n", qe->chan->name);
2372                         res = 0;
2373                 }
2374                 
2375                 ast_mutex_unlock(&qe->parent->lock);
2376         }
2377
2378         return res;
2379 }
2380
2381 static int wait_our_turn(struct queue_ent *qe, int ringing, enum queue_result *reason)
2382 {
2383         int res = 0;
2384
2385         /* This is the holding pen for callers 2 through maxlen */
2386         for (;;) {
2387                 enum queue_member_status stat;
2388
2389                 if (is_our_turn(qe))
2390                         break;
2391
2392                 /* If we have timed out, break out */
2393                 if (qe->expire && (time(NULL) > qe->expire)) {
2394                         *reason = QUEUE_TIMEOUT;
2395                         break;
2396                 }
2397
2398                 stat = get_member_status(qe->parent, qe->max_penalty);
2399
2400                 /* leave the queue if no agents, if enabled */
2401                 if (qe->parent->leavewhenempty && (stat == QUEUE_NO_MEMBERS)) {
2402                         *reason = QUEUE_LEAVEEMPTY;
2403                         ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2404                         leave_queue(qe);
2405                         break;
2406                 }
2407
2408                 /* leave the queue if no reachable agents, if enabled */
2409                 if ((qe->parent->leavewhenempty == QUEUE_EMPTY_STRICT) && (stat == QUEUE_NO_REACHABLE_MEMBERS || stat == QUEUE_NO_UNPAUSED_REACHABLE_MEMBERS)) {
2410                         *reason = QUEUE_LEAVEUNAVAIL;
2411                         ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2412                         leave_queue(qe);
2413                         break;
2414                 }
2415                 if ((qe->parent->leavewhenempty == QUEUE_EMPTY_LOOSE) && (stat == QUEUE_NO_REACHABLE_MEMBERS)) {
2416                         *reason = QUEUE_LEAVEUNAVAIL;
2417                         ast_queue_log(qe->parent->name, qe->chan->uniqueid, "NONE", "EXITEMPTY", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2418                         leave_queue(qe);
2419                         break;
2420                 }
2421
2422                 /* Make a position announcement, if enabled */
2423                 if (qe->parent->announcefrequency &&
2424                         (res = say_position(qe,ringing)))
2425                         break;
2426
2427                 /* Make a periodic announcement, if enabled */
2428                 if (qe->parent->periodicannouncefrequency &&
2429                         (res = say_periodic_announcement(qe,ringing)))
2430                         break;
2431
2432                 /* Wait a second before checking again */
2433                 if ((res = ast_waitfordigit(qe->chan, RECHECK * 1000))) {
2434                         if (res > 0 && !valid_exit(qe, res))
2435                                 res = 0;
2436                         else
2437                                 break;
2438                 }
2439         }
2440
2441         return res;
2442 }
2443
2444 static int update_queue(struct call_queue *q, struct member *member, int callcompletedinsl)
2445 {
2446         ast_mutex_lock(&q->lock);
2447         time(&member->lastcall);
2448         member->calls++;
2449         q->callscompleted++;
2450         if (callcompletedinsl)
2451                 q->callscompletedinsl++;
2452         ast_mutex_unlock(&q->lock);
2453         return 0;
2454 }
2455
2456 static int calc_metric(struct call_queue *q, struct member *mem, int pos, struct queue_ent *qe, struct callattempt *tmp)
2457 {
2458         if (qe->max_penalty && (mem->penalty > qe->max_penalty))
2459                 return -1;
2460
2461         switch (q->strategy) {
2462         case QUEUE_STRATEGY_RINGALL:
2463                 /* Everyone equal, except for penalty */
2464                 tmp->metric = mem->penalty * 1000000;
2465                 break;
2466         case QUEUE_STRATEGY_RRMEMORY:
2467                 if (pos < q->rrpos) {
2468                         tmp->metric = 1000 + pos;
2469                 } else {
2470                         if (pos > q->rrpos)
2471                                 /* Indicate there is another priority */
2472                                 q->wrapped = 1;
2473                         tmp->metric = pos;
2474                 }
2475                 tmp->metric += mem->penalty * 1000000;
2476                 break;
2477         case QUEUE_STRATEGY_RANDOM:
2478                 tmp->metric = ast_random() % 1000;
2479                 tmp->metric += mem->penalty * 1000000;
2480                 break;
2481         case QUEUE_STRATEGY_FEWESTCALLS:
2482                 tmp->metric = mem->calls;
2483                 tmp->metric += mem->penalty * 1000000;
2484                 break;
2485         case QUEUE_STRATEGY_LEASTRECENT:
2486                 if (!mem->lastcall)
2487                         tmp->metric = 0;
2488                 else
2489                         tmp->metric = 1000000 - (time(NULL) - mem->lastcall);
2490                 tmp->metric += mem->penalty * 1000000;
2491                 break;
2492         default:
2493                 ast_log(LOG_WARNING, "Can't calculate metric for unknown strategy %d\n", q->strategy);
2494                 break;
2495         }
2496         return 0;
2497 }
2498
2499 enum agent_complete_reason {
2500         CALLER,
2501         AGENT,
2502         TRANSFER
2503 };
2504
2505 static void send_agent_complete(const struct queue_ent *qe, const char *queuename,
2506         const struct ast_channel *peer, const struct member *member, time_t callstart,
2507         char *vars, size_t vars_len, enum agent_complete_reason rsn)
2508 {
2509         const char *reason;
2510
2511         if (!qe->parent->eventwhencalled)
2512                 return;
2513
2514         switch (rsn) {
2515         case CALLER:
2516                 reason = "caller";
2517                 break;
2518         case AGENT:
2519                 reason = "agent";
2520                 break;
2521         case TRANSFER:
2522                 reason = "transfer";
2523                 break;
2524         }
2525
2526         manager_event(EVENT_FLAG_AGENT, "AgentComplete",
2527                 "Queue: %s\r\n"
2528                 "Uniqueid: %s\r\n"
2529                 "Channel: %s\r\n"
2530                 "Member: %s\r\n"
2531                 "MemberName: %s\r\n"
2532                 "HoldTime: %ld\r\n"
2533                 "TalkTime: %ld\r\n"
2534                 "Reason: %s\r\n"
2535                 "%s",
2536                 queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
2537                 (long)(callstart - qe->start), (long)(time(NULL) - callstart), reason,
2538                 qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, vars_len) : "");
2539 }
2540
2541 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)
2542 {
2543         struct member *cur;
2544         struct callattempt *outgoing = NULL; /* the list of calls we are building */
2545         int to, orig;
2546         char oldexten[AST_MAX_EXTENSION]="";
2547         char oldcontext[AST_MAX_CONTEXT]="";
2548         char queuename[256]="";
2549         char interfacevar[256]="";
2550         struct ast_channel *peer;
2551         struct ast_channel *which;
2552         struct callattempt *lpeer;
2553         struct member *member;
2554         struct ast_app *app;
2555         int res = 0, bridge = 0;
2556         int numbusies = 0;
2557         int x=0;
2558         char *announce = NULL;
2559         char digit = 0;
2560         time_t callstart;
2561         time_t now = time(NULL);
2562         struct ast_bridge_config bridge_config;
2563         char nondataquality = 1;
2564         char *agiexec = NULL;
2565         char *macroexec = NULL;
2566         char *gosubexec = NULL;
2567         int ret = 0;
2568         const char *monitorfilename;
2569         const char *monitor_exec;
2570         const char *monitor_options;
2571         char tmpid[256], tmpid2[256];
2572         char meid[1024], meid2[1024];
2573         char mixmonargs[1512];
2574         struct ast_app *mixmonapp = NULL;
2575         char *p;
2576         char vars[2048];
2577         int forwardsallowed = 1;
2578         int callcompletedinsl;
2579         struct ao2_iterator memi;
2580
2581         memset(&bridge_config, 0, sizeof(bridge_config));
2582         time(&now);
2583                 
2584         for (; options && *options; options++)
2585                 switch (*options) {
2586                 case 't':
2587                         ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_REDIRECT);
2588                         break;
2589                 case 'T':
2590                         ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_REDIRECT);
2591                         break;
2592                 case 'w':
2593                         ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_AUTOMON);
2594                         break;
2595                 case 'W':
2596                         ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_AUTOMON);
2597                         break;
2598                 case 'd':
2599                         nondataquality = 0;
2600                         break;
2601                 case 'h':
2602                         ast_set_flag(&(bridge_config.features_callee), AST_FEATURE_DISCONNECT);
2603                         break;
2604                 case 'H':
2605                         ast_set_flag(&(bridge_config.features_caller), AST_FEATURE_DISCONNECT);
2606                         break;
2607                 case 'n':
2608                         if (qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY)
2609                                 (*tries)++;
2610                         else
2611                                 *tries = qe->parent->membercount;
2612                         *noption = 1;
2613                         break;
2614                 case 'i':
2615                         forwardsallowed = 0;
2616                         break;
2617                 }
2618
2619         /* Hold the lock while we setup the outgoing calls */
2620         if (use_weight)
2621                 AST_LIST_LOCK(&queues);
2622         ast_mutex_lock(&qe->parent->lock);
2623         ast_debug(1, "%s is trying to call a queue member.\n",
2624                                                         qe->chan->name);
2625         ast_copy_string(queuename, qe->parent->name, sizeof(queuename));
2626         if (!ast_strlen_zero(qe->announce))
2627                 announce = qe->announce;
2628         if (!ast_strlen_zero(announceoverride))
2629                 announce = announceoverride;
2630
2631         memi = ao2_iterator_init(qe->parent->members, 0);
2632         while ((cur = ao2_iterator_next(&memi))) {
2633                 struct callattempt *tmp = ast_calloc(1, sizeof(*tmp));
2634
2635                 if (!tmp) {
2636                         ao2_ref(cur, -1);
2637                         ast_mutex_unlock(&qe->parent->lock);
2638                         if (use_weight)
2639                                 AST_LIST_UNLOCK(&queues);
2640                         goto out;
2641                 }
2642                 tmp->stillgoing = -1;
2643                 tmp->member = cur;
2644                 tmp->oldstatus = cur->status;
2645                 tmp->lastcall = cur->lastcall;
2646                 ast_copy_string(tmp->interface, cur->interface, sizeof(tmp->interface));
2647                 /* Special case: If we ring everyone, go ahead and ring them, otherwise
2648                    just calculate their metric for the appropriate strategy */
2649                 if (!calc_metric(qe->parent, cur, x++, qe, tmp)) {
2650                         /* Put them in the list of outgoing thingies...  We're ready now.
2651                            XXX If we're forcibly removed, these outgoing calls won't get
2652                            hung up XXX */
2653                         tmp->q_next = outgoing;
2654                         outgoing = tmp;         
2655                         /* If this line is up, don't try anybody else */
2656                         if (outgoing->chan && (outgoing->chan->_state == AST_STATE_UP))
2657                                 break;
2658                 } else {
2659                         ao2_ref(cur, -1);
2660                         free(tmp);
2661                 }
2662         }
2663         if (qe->expire && (!qe->parent->timeout || (qe->expire - now) <= qe->parent->timeout))
2664                 to = (qe->expire - now) * 1000;
2665         else
2666                 to = (qe->parent->timeout) ? qe->parent->timeout * 1000 : -1;
2667         orig = to;
2668         ring_one(qe, outgoing, &numbusies);
2669         ast_mutex_unlock(&qe->parent->lock);
2670         if (use_weight)
2671                 AST_LIST_UNLOCK(&queues);
2672         lpeer = wait_for_answer(qe, outgoing, &to, &digit, numbusies, ast_test_flag(&(bridge_config.features_caller), AST_FEATURE_DISCONNECT), forwardsallowed);
2673         ast_mutex_lock(&qe->parent->lock);
2674         if (qe->parent->strategy == QUEUE_STRATEGY_RRMEMORY) {
2675                 store_next(qe, outgoing);
2676         }
2677         ast_mutex_unlock(&qe->parent->lock);
2678         peer = lpeer ? lpeer->chan : NULL;
2679         if (!peer) {
2680                 if (to) {
2681                         /* Must gotten hung up */
2682                         res = -1;
2683                 } else {
2684                         /* User exited by pressing a digit */
2685                         res = digit;
2686                 }
2687                 if (res == -1)
2688                         ast_debug(1, "%s: Nobody answered.\n", qe->chan->name);
2689         } else { /* peer is valid */
2690                 /* Ah ha!  Someone answered within the desired timeframe.  Of course after this
2691                    we will always return with -1 so that it is hung up properly after the
2692                    conversation.  */
2693                 qe->handled++;
2694                 if (!strcmp(qe->chan->tech->type, "Zap"))
2695                         ast_channel_setoption(qe->chan, AST_OPTION_TONE_VERIFY, &nondataquality, sizeof(nondataquality), 0);
2696                 if (!strcmp(peer->tech->type, "Zap"))
2697                         ast_channel_setoption(peer, AST_OPTION_TONE_VERIFY, &nondataquality, sizeof(nondataquality), 0);
2698                 /* Update parameters for the queue */
2699                 time(&now);
2700                 recalc_holdtime(qe, (now - qe->start));
2701                 ast_mutex_lock(&qe->parent->lock);
2702                 callcompletedinsl = ((now - qe->start) <= qe->parent->servicelevel);
2703                 ast_mutex_unlock(&qe->parent->lock);
2704                 member = lpeer->member;
2705                 hangupcalls(outgoing, peer);
2706                 outgoing = NULL;
2707                 if (announce || qe->parent->reportholdtime || qe->parent->memberdelay) {
2708                         int res2;
2709
2710                         res2 = ast_autoservice_start(qe->chan);
2711                         if (!res2) {
2712                                 if (qe->parent->memberdelay) {
2713                                         ast_log(LOG_NOTICE, "Delaying member connect for %d seconds\n", qe->parent->memberdelay);
2714                                         res2 |= ast_safe_sleep(peer, qe->parent->memberdelay * 1000);
2715                                 }
2716                                 if (!res2 && announce) {
2717                                         play_file(peer, announce);
2718                                 }
2719                                 if (!res2 && qe->parent->reportholdtime) {
2720                                         if (!play_file(peer, qe->parent->sound_reporthold)) {
2721                                                 int holdtime;
2722
2723                                                 time(&now);
2724                                                 holdtime = abs((now - qe->start) / 60);
2725                                                 if (holdtime < 2) {
2726                                                         play_file(peer, qe->parent->sound_lessthan);
2727                                                         ast_say_number(peer, 2, AST_DIGIT_ANY, peer->language, NULL);
2728                                                 } else
2729                                                         ast_say_number(peer, holdtime, AST_DIGIT_ANY, peer->language, NULL);
2730                                                 play_file(peer, qe->parent->sound_minutes);
2731                                         }
2732                                 }
2733                         }
2734                         res2 |= ast_autoservice_stop(qe->chan);
2735                         if (ast_check_hangup(peer)) {
2736                                 /* Agent must have hung up */
2737                                 ast_log(LOG_WARNING, "Agent on %s hungup on the customer.\n", peer->name);
2738                                 ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "AGENTDUMP", "%s", "");
2739                                 record_abandoned(qe);
2740                                 if (qe->parent->eventwhencalled)
2741                                         manager_event(EVENT_FLAG_AGENT, "AgentDump",
2742                                                         "Queue: %s\r\n"
2743                                                         "Uniqueid: %s\r\n"
2744                                                         "Channel: %s\r\n"
2745                                                         "Member: %s\r\n"
2746                                                         "MemberName: %s\r\n"
2747                                                         "%s",
2748                                                         queuename, qe->chan->uniqueid, peer->name, member->interface, member->membername,
2749                                                         qe->parent->eventwhencalled == QUEUE_EVENT_VARIABLES ? vars2manager(qe->chan, vars, sizeof(vars)) : "");
2750                                 ast_hangup(peer);
2751                                 goto out;
2752                         } else if (res2) {
2753                                 /* Caller must have hung up just before being connected*/
2754                                 ast_log(LOG_NOTICE, "Caller was about to talk to agent on %s but the caller hungup.\n", peer->name);
2755                                 ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "ABANDON", "%d|%d|%ld", qe->pos, qe->opos, (long) time(NULL) - qe->start);
2756                                 record_abandoned(qe);
2757                                 ast_hangup(peer);
2758                                 return -1;
2759                         }
2760                 }
2761                 /* Stop music on hold */
2762                 if (ringing)
2763                         ast_indicate(qe->chan,-1);
2764                 else
2765                         ast_moh_stop(qe->chan);
2766                 /* If appropriate, log that we have a destination channel */
2767                 if (qe->chan->cdr)
2768                         ast_cdr_setdestchan(qe->chan->cdr, peer->name);
2769                 /* Make sure channels are compatible */
2770                 res = ast_channel_make_compatible(qe->chan, peer);
2771                 if (res < 0) {
2772                         ast_queue_log(queuename, qe->chan->uniqueid, member->membername, "SYSCOMPAT", "%s", "");
2773                         ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", qe->chan->name, peer->name);
2774                         record_abandoned(qe);
2775                         ast_hangup(peer);
2776                         return -1;
2777                 }
2778
2779                 /* Play announcement to the caller telling it's his turn if defined */
2780                 if (!ast_strlen_zero(qe->parent->sound_callerannounce)) {
2781                         if (play_file(qe->chan, qe->parent->sound_callerannounce))
2782                                 ast_log(LOG_WARNING, "Announcement file '%s' is unavailable, continuing anyway...\n", qe->parent->sound_callerannounce);
2783                 }
2784
2785                 ast_mutex_lock(&qe->parent->lock);
2786                 /* if setinterfacevar is defined, make member variables available to the channel */
2787                 /* use  pbx_builtin_setvar to set a load of variables with one call */
2788                 if (qe->parent->setinterfacevar) {
2789                         snprintf(interfacevar,sizeof(interfacevar), "MEMBERINTERFACE=%s|MEMBERNAME=%s|MEMBERCALLS=%d|MEMBERLASTCALL=%ld|MEMBERPENALTY=%d|MEMBERDYNAMIC=%d|MEMBERREALTIME=%d",
2790                                 member->interface, member->membername, member->calls, (long)member->lastcall, member->penalty, member->dynamic, member->realtime);
2791                         pbx_builtin_setvar(qe->chan, interfacevar);
2792                 }
2793                 
2794                 /* if setqueueentryvar is defined, make queue entry (i.e. the caller) variables available to the channel */
2795                 /* use  pbx_builtin_setvar to set a load of variables with one call */
2796                 if (qe->parent->setqueueentryvar) {
2797                         snprintf(interfacevar,sizeof(interfacevar), "QEHOLDTIME=%ld|QEORIGINALPOS=%d",
2798                                 (long) time(NULL) - qe->start, qe->opos);
2799                         pbx_builtin_setvar(qe->chan, interfacevar);
2800                 }
2801         
2802                 /* try to set queue variables if configured to do so*/
2803                 set_queue_variables(qe);
2804                 ast_mutex_unlock(&qe->parent->lock);
2805                 
2806                 /* Begin Monitoring */
2807                 if (qe->parent->monfmt && *qe->parent->monfmt) {
2808                         if (!qe->parent->montype) {
2809                                 ast_debug(1, "Starting Monitor as requested.\n");
2810                                 monitorfilename = pbx_builtin_getvar_helper(qe->chan, "MONITOR_FILENAME");
2811                                 if (pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC") || pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC_ARGS"))
2812                                         which = qe->chan;
2813                                 else
2814                                         which = peer;
2815                                 if (monitorfilename)
2816                                         ast_monitor_start(which, qe->parent->monfmt, monitorfilename, 1, X_REC_IN | X_REC_OUT);
2817                                 else if (qe->chan->cdr)
2818                                         ast_monitor_start(which, qe->parent->monfmt, qe->chan->cdr->uniqueid, 1, X_REC_IN | X_REC_OUT);
2819                                 else {
2820                                         /* Last ditch effort -- no CDR, make up something */
2821                                         snprintf(tmpid, sizeof(tmpid), "chan-%lx", ast_random());
2822                                         ast_monitor_start(which, qe->parent->monfmt, tmpid, 1, X_REC_IN | X_REC_OUT);
2823                                 }
2824                                 if (qe->parent->monjoin)
2825                                         ast_monitor_setjoinfiles(which, 1);
2826                         } else {
2827                                 ast_debug(1, "Starting MixMonitor as requested.\n");
2828                                 monitorfilename = pbx_builtin_getvar_helper(qe->chan, "MONITOR_FILENAME");
2829                                 if (!monitorfilename) {
2830                                         if (qe->chan->cdr)
2831                                                 ast_copy_string(tmpid, qe->chan->cdr->uniqueid, sizeof(tmpid)-1);
2832                                         else
2833                                                 snprintf(tmpid, sizeof(tmpid), "chan-%lx", ast_random());
2834                                 } else {
2835                                         ast_copy_string(tmpid2, monitorfilename, sizeof(tmpid2)-1);
2836                                         for (p = tmpid2; *p ; p++) {
2837                                                 if (*p == '^' && *(p+1) == '{') {
2838                                                         *p = '$';
2839                                                 }
2840                                         }
2841
2842                                         memset(tmpid, 0, sizeof(tmpid));
2843                                         pbx_substitute_variables_helper(qe->chan, tmpid2, tmpid, sizeof(tmpid) - 1);
2844                                 }
2845
2846                                 monitor_exec = pbx_builtin_getvar_helper(qe->chan, "MONITOR_EXEC");
2847                                 monitor_options = pbx_builtin_getvar_helper(qe->chan, "MONITOR_OPTIONS");
2848
2849                                 if (monitor_exec) {
2850                                         ast_copy_string(meid2, monitor_exec, sizeof(meid2)-1);
2851                                         for (p = meid2; *p ; p++) {
2852                                                 if (*p == '^' && *(p+1) == '{') {
2853                                                         *p = '$';
2854                                                 }
2855                                         }
2856
2857                                         memset(meid, 0, sizeof(meid));
2858                                         pbx_substitute_variables_helper(qe->chan, meid2, meid, sizeof(meid) - 1);
2859                                 }
2860         
2861                                 snprintf(tmpid2, sizeof(tmpid2)-1, "%s.%s", tmpid, qe->parent->monfmt);
2862
2863                                 mixmonapp = pbx_findapp("MixMonitor");
2864
2865                                 if (strchr(tmpid2, '|')) {
2866                                         ast_log(LOG_WARNING, "monitor-format (in queues.conf) and MONITOR_FILENAME cannot contain a '|'! Not recording.\n");
2867                                         mixmonapp = NULL;
2868                                 }
2869
2870                                 if (!monitor_options)
2871                                         monitor_options = "";
2872                                 
2873                                 if (strchr(monitor_options, '|')) {
2874                                         ast_log(LOG_WARNING, "MONITOR_OPTIONS cannot contain a '|'! Not recording.\n");
2875                                         mixmonapp = NULL;
2876                                 }
2877
2878                                 if (mixmonapp) {
2879                                         if (!ast_strlen_zero(monitor_exec))
2880                                                 snprintf(mixmonargs, sizeof(mixmonargs)-1, "%s|b%s|%s", tmpid2, monitor_options, monitor_exec);
2881                                         else
2882                                                 snprintf(mixmonargs, sizeof(mixmonargs)-1, "%s|b%s", tmpid2, monitor_options);
2883                                                 
2884                                         ast_debug(1, "Arguments being passed to MixMonitor: %s\n", mixmonargs);
2885                                         /* We purposely lock the CDR so that pbx_exec does not update the application data */
2886                                         if (qe->chan->cdr)
2887                                                 ast_set_flag(qe->chan->cdr, AST_CDR_FLAG_LOCKED);
2888                                         ret = pbx_exec(qe->chan, mixmonapp, mixmonargs);
2889                                         if (qe->chan->cdr)
2890                                                 ast_clear_flag(qe->chan->cdr, AST_CDR_FLAG_LOCKED);
2891
2892                                 } else
2893                                         ast_log(LOG_WARNING, "Asked to run MixMonitor on this call, but cannot find the MixMonitor app!\n");
2894
2895                         }
2896                 }
2897                 /* Drop out of the queue at this point, to prepare for next caller */
2898                 leave_queue(qe);                        
2899                 if (!ast_strlen_zero(url) && ast_channel_supports_html(peer)) {
2900                         ast_debug(1, "app_queue: sendurl=%s.\n", url);
2901                         ast_channel_sendurl(peer, url);
2902                 }
2903                 
2904                 /* run a macro for this connection if defined. The macro simply returns, no action is taken on the result */
2905                 /* use macro from dialplan if passed as a option, otherwise use the default queue macro */
2906                 if (!ast_strlen_zero(macro)) {
2907                                 macroexec = ast_strdupa(macro);
2908                 } else {
2909                         if (qe->parent->membermacro)
2910                                 macroexec = ast_strdupa(qe->parent->membermacro);
2911                 }
2912
2913                 if (!ast_strlen_zero(macroexec)) {
2914                         ast_debug(1, "app_queue: macro=%s.\n", macroexec);
2915                         
2916                         res = ast_autoservice_start(qe->chan);
2917                         if (res) {
2918                                 ast_log(LOG_ERROR, "Unable to start autoservice on calling channel\n");
2919                                 res = -1;
2920                         }
2921                         
2922                         app = pbx_findapp("Macro");
2923                         
2924                         if (app) {
2925                                 res = pbx_exec(qe->chan, app, macroexec);
2926                                 ast_debug(1, "Macro exited with status %d\n", res);
2927                                 res = 0;
2928                         } else {
2929                                 ast_log(LOG_ERROR, "Could not find application Macro\n");
2930                                 res = -1;
2931                         }
2932                 
2933                         if (ast_autoservice_stop(qe->chan) < 0) {
2934                                 ast_log(LOG_ERROR, "Could not stop autoservice on calling channel\n");
2935                                 res = -1;
2936                         }
2937                 }
2938