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