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