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