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