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