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