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